本文主要是介绍NSArray、NSMutableArray相关,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
移除相同的
NSMutableArray *arr001 = [_selectedArr mutableCopy];
for(int i=0;i<_selectedArr.count;i++){
ContactPersonInfo *dic = _selectedArr[i];
NSMutableArray *arr002 = [NSMutableArray array];
for(int j=0;j<i;j++){
[arr002 addObject:_selectedArr[j]];
}
if (arr002.count>0) {
for(ContactPersonInfo *dic0 in arr002){
if ([dic0.user_id integerValue] == [dic.user_id integerValue] ) {
[arr001 removeObject:dic];
}
}
}
}
排序
NSArray *result = [arr001 sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
NSDictionary *dic1 = obj1;
NSDictionary *dic2 = obj2;
NSNumber *num1 = dic1[@"num"] ;
NSNumber *num2 = dic2[@"num"] ;
return [num1 compare:num2]; //升序
}];
1.求和、最值
float sum = [[arr valueForKeyPath:@"@sum.floatValue"] floatValue];//求和
float avg = [[arr valueForKeyPath:@"@avg.floatValue"] floatValue];//求平均值
float max = [[arr valueForKeyPath:@"@max.floatValue"] floatValue];//求最大值
float min = [[arr valueForKeyPath:@"@min.floatValue"] floatValue];//求最小值
NSArray
1.是否包含某个元素
[array containsObject: str]
NSMutableArray
1.替换对象
NSMutableArray *newArray = [_regionDetailDataArr mutableCopy];
[newArray replaceObjectAtIndex:_selectedIndex withObject:newDic];
_regionDetailDataArr = newArray;
数组与 json 互转
json->nsarray
-(id)jsonToObject:(NSString *)json{
//string转data
NSData * jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
//json解析
id obj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
return obj;
}
nsarray -> json
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr
options:kNilOptions
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
排序
-
NSArray *arr = @[@"fdaf", @"fdafd", @"1", @"fadfdafdsaf"];
-
NSArray *a0 = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
-
NSUInteger len0 = [(NSString *)obj1 length];
-
NSUInteger len1 = [(NSString *)obj2 length];
-
return len0 > len1 ? NSOrderedAscending : NSOrderedDescending;
-
}];
-
NSLog(@"origin:%@\nsorted:%@", arr, a0);
-
NSArray *newArray = [allUserName sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
-
NSUInteger len0 = [(NSString*)obj1 length];
-
NSUInteger len1 = [(NSString*)obj2 length];
-
return len0>len1 ? NSOrderedDescending : NSOrderedAscending;
-
}];
这篇关于NSArray、NSMutableArray相关的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!