NSArray *array = @[@"string 1", @"string 3", @"string 4", @"string 2" ]; //使用block,枚举所有数组元素,相当于forin循环 NSLog(@"排序之前:\n"); [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSLog(@"object at index %d = %@\n", idx, obj); }]; NSLog(@"排序: \n"); //注意NSComparisonResult的用法 NSMutableArray *sortArray = [NSMutableArray arrayWithArray:array]; //sortUsingComparator方法只可以直接改变NSMutableArray元素顺序 [sortArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) { NSString *str1 = obj1; NSString *str2 = obj2; return [str1 compare:str2]; }]; [sortArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSLog(@"object at index %d = %@\n", idx, obj); }]; //NSArray是只读的,只能使用sortedArrayUsingComparator,并重新赋值 array = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) { NSString *str1 = obj1; NSString *str2 = obj2; return [str1 compare:str2]; }]; [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSLog(@"object at index %d = %@\n", idx, obj); }];
NSDictionary、NSMutableDictionary也有类似
NSSet与NSArray的区别,在于同一个对象只允许添加一次,而NSArray没有这个限制