iOS Objective-C 数组排序:根据imgCode大小排序
{"title":"iOS Objective-C 数组排序:根据imgCode大小排序","description":"本文介绍了如何使用 Objective-C 的 sortedArrayUsingComparator 方法,根据数组中字典的 imgCode 字段大小进行排序,并附带代码示例。","keywords":"iOS, Objective-C, 数组排序, sortedArrayUsingComparator, imgCode, NSDictionary, NSComparisonResult","content":"要根据数组里面imgCode的大小进行排序,可以使用以下代码:\n\nobject-c\nNSArray *sortedArray = [self.dataSource sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {\n NSDictionary *dict1 = (NSDictionary *)obj1;\n NSDictionary *dict2 = (NSDictionary *)obj2;\n \n NSInteger imgCode1 = [[dict1 objectForKey:@"imgCode"] integerValue];\n NSInteger imgCode2 = [[dict2 objectForKey:@"imgCode"] integerValue];\n \n if (imgCode1 < imgCode2) {\n return NSOrderedAscending;\n } else if (imgCode1 > imgCode2) {\n return NSOrderedDescending;\n } else {\n return NSOrderedSame;\n }\n}];\n\nself.dataSource = [NSMutableArray arrayWithArray:sortedArray];\n\n\n这段代码使用了sortedArrayUsingComparator:方法来进行排序。在比较器中,首先获取每个字典中的imgCode值,然后根据大小返回不同的NSComparisonResult值。最后,将排序后的数组赋值给self.dataSource。"}
原文地址: https://www.cveoy.top/t/topic/qijF 著作权归作者所有。请勿转载和采集!