根据另一个NSArray的字符串对NSMutableArray进行排序

时间:2012-12-03 09:01:08

标签: objective-c ios nsmutablearray nsarray

我有一个NSArray字符串,我想用作排序顺序:

NSArray *permissionTypes = [NSArray arrayWithObjects:@"Read", @"Write", @"Admin", nil];

然后我有一个NSMutableArray可能有也可能没有这三种权限类型,但有时它只有2,有时是1,但我仍然希望它根据我的permissionsTypes进行排序阵列。

NSMutableArray *order = [NSMutableArray arrayWithArray:[permissions allKeys]];

如何根据我使用order数组作为键来正确排序permissionTypes数组?

4 个答案:

答案 0 :(得分:3)

我会通过创建一个结构或一个对象来保存权限类型。

然后你可以......

PermissionType
--------------
Name: Read
Order: 1

PermissionType
--------------
Name: Write
Order: 2

等等。

然后你只需要这些对象的实际数组,你可以按顺序值排序。

[array sortUsingComparator:^NSComparisonResult(PermissionType *obj1, PermissionType *obj2) {
        return [obj1.order compare:obj2.order];
    }];

这将按订单字段对数组进行排序。

答案 1 :(得分:3)

NSMutableArray *sortDescriptors = [NSMutableArray array]; 

for (NSString *type in permissionTypes) {
    NSSortDescriptor *descriptor = [[[NSSortDescriptor alloc] initWithKey:type ascending:YES] autorelease];

    [sortDescriptors addObject:descriptor];
}

sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];

答案 2 :(得分:0)

使用您喜欢的NSMutableArray上的任何排序方法,您将提供用于比较两个元素的块或选择器。在该块/选择器中,而不是直接比较传入的两个字符串,使用permissionTypesindexOfObject:数组中查找每个字符串,并比较返回的结果索引值。

答案 3 :(得分:0)

我建议你采用另一种方法:

- (void)viewDidLoad
{
[super viewDidLoad];

arrayPermissions = [[NSMutableArray alloc] init];


NSDictionary *dicRead = [NSDictionary dictionaryWithObjectsAndKeys:
                              @"Read", @"Permission", nil];

NSDictionary *dicWrite = [NSDictionary dictionaryWithObjectsAndKeys:
                               @"Write", @"Permission", nil];

NSDictionary *dicAdmin = [NSDictionary dictionaryWithObjectsAndKeys:
                              @"Admin", @"Permission", nil];

NSLog(@"my dicRead = %@", dicRead);
NSLog(@"my dicWrite = %@", dicWrite);
NSLog(@"my dicAdmin = %@", dicAdmin);

[arrayPermissions addObject:dicRead];
[arrayPermissions addObject:dicWrite];
[arrayPermissions addObject:dicAdmin];

NSLog(@"arrayPermissions is: %@", arrayPermissions);

// create a temporary Dict again

NSDictionary *temp =[[NSDictionary alloc]
                     initWithObjectsAndKeys: arrayPermissions, @"Permission", nil];

// declare one dictionary in header class for global use and called "filteredDict"
self.filteredDict = temp;

self.sortedKeys =[[self.filteredDict allKeys]
                  sortedArrayUsingSelector:@selector(compare:)];


NSLog(@"sortedKeys is: %i", sortedKeys.count);
NSLog(@"sortedKeys is: %@", sortedKeys);

}

希望帮助