1

我有一个NSArray要用作排序顺序的字符串:

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

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

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

如何始终order根据我使用permissionTypes数组作为键对数组进行正确排序?

4

4 回答 4

3

I would go about this by creating a struct or an object to hold the permission types.

Then you can have...

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

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

and so on.

Then you only need the actual array of these objects and you can sort by the order value.

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

This will order the array by the order field.

于 2012-12-03T09:07:21.560 回答
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];
于 2012-12-03T09:14:18.217 回答
0

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

于 2012-12-03T09:11:33.403 回答
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);

}

希望帮助

于 2013-04-18T14:56:20.863 回答