按字母顺序排列的多维数组(obj c)

时间:2013-04-21 17:07:58

标签: objective-c xcode multidimensional-array sorting

我有一个数组,它包含多个其他数组,每个数组都包含两个字符串。我想根据子数组中的第一个字符串按字母顺序对父数组中的项进行排序。我该怎么做?

父阵列---                childArray1(bString,string)                childArray2(dString,string)                childArray3(cString,string)                childArray4(aString,string)

更改为 - >                childArray4(aString,string)                childArray1(bString,string)                childArray3(cString,string)                childArray2(dString,string)

因此,每个子数组中的第一个字符串确定父数组中子数组的索引

1 个答案:

答案 0 :(得分:1)

最简单的解决方案是不使用多维数组,而是使用compare:方法为值使用自定义对象,例如

@interface MyObject : NSObject

@property (nonatomic, strong, readwrite) NSString* firstString;
@property (nonatomic, strong, readwrite) NSString* secondString;

- (NSComparisonResult)compare:(MyObject*)object;

@end


@implementation MyObject

- (NSComparisonResult)compare:(MyObject*)object {
   return [self.firstString compare:object.firstString];
}

@end

然后使用:

对数组进行排序
NSArray* sortedObjects = [array sortedArrayUsingSelector:@selector(compare:)];

如果你想坚持你的实施,那么

NSArray* sortedObjects = [array sortedArrayUsingComparator:^(id obj1, id obj2) {
   NSString* string1 = [obj1 objectAtIndex:0];
   NSString* string2 = [obj2 objectAtIndex:0];

   return [string1 compare:string2];
}];