我在排序我的一个NSMutableArrays时遇到了麻烦。
阵列设置如下
classesArray = [[NSMutableArray alloc] initWithObjects:nil];
NSMutableArray *tmpClassMembers = [[[NSMutableArray alloc] initWithObjects:nil] autorelease];
//tmpClassMembers gets populated
//hold an array with the class ID, name and class members.
//classID and classname are just strings essentially
NSMutableArray *tmpClass = [[NSMutableArray alloc] initWithObjects:msClass.ClassId,msClass.ClassName,tmpClassMembers,nil];
//add the new class to the main class array
[classesArray addObject:tmpClass];
示例顺序是(这些存储在数组中的元素[1](className)
中)classesArray[0][1] = "3. Science 5B"
classesArray[1][1] = "4. Geography 6S"
classesArray[2][1] = "2. Biology 6T"
classesArray[3][1] = "1. English 1A"
我尝试过使用块排序,但它似乎没有做任何事情。我期望它根据数组中的第二个元素([1])进行排序。这应该是类名。
NSArray *sortedArray = [classesArray sortedArrayUsingComparator:^(id a, id b) {
NSString *numA = [a objectAtIndex:1]; //eg: "1. English 1A"
NSString *numB = [b objectAtIndex:1]; //eg: "3. Science 5B
//NSLog(@"a=%@, b=%@", numA, numB);
return [numB compare:numA];
}];
我希望classesArray符合以下顺序
classesArray[0][1] = "1. English 1A"
classesArray[1][1] = "2. Biology 6T"
classesArray[2][1] = "3. Science 5B"
classesArray[3][1] = "4. Geography 6S"
所以基本上它应该对字符串进行排序 - 当然它会看到每个字符串都以数字开头然后对其进行排序?
我无法将数字作为要排序的ID,因为id实际上类似于DF345345-ERERT56,并且没有任何相关性。
我哪里错了?!
答案 0 :(得分:0)
我不会使用tmpClasses数组。如果您创建一个名为MyClass的类,其中包含变量的属性:
@interface MyClass : NSObject
@property (nonatomic,retain) NSString* classID;
@property (nonatomic,retain) NSString* className;
@property (nonatomic,retain) NSMutableArray* classMembers;
然后您可以使用此方法对MyClass对象数组进行排序:
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"classID"
ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
arrayOfMyClassObjects = [arrayOfMyClassObjects sortedArrayUsingDescriptors:sortDescriptors];