简体   繁体   中英

sorting NSArray on ID

I have an NSArray with statussen of people. (ex. Online, Offline,...) Now I got this from my core database. And that core database got the objects from a webservice. Now I need another status (Logout) to the end of my array. This is what I do in code.

_arrStatus = [[NSMutableArray alloc]init];
    for (Status *status in matches) {
        [_arrStatus addObject:status];
    }
    BOOL logout = false;
    for (Status *status in matches) {
        if([status.cs_id isEqualToNumber:[NSNumber numberWithInt:0]]){
            logout = true;
        }
    }
    if(!logout){
        Status* newStatus = [NSEntityDescription insertNewObjectForEntityForName:@"Statussen" inManagedObjectContext:context];
        newStatus.cs_id = [NSNumber numberWithInt:0];
        newStatus.cs_name = @"Logout";
        [_arrStatus addObject:newStatus];
    } 
    NSError *error = nil;
    [context save:&error];

Like you can see I gave my 'Logout status' the ID 0, because I am sure that, that ID is available. Here is how to order of my NSArray and the ID's.

  • Logout -> ID 0
  • Online -> ID 1
  • Offline -> ID 2
  • Absent -> ID 3

Now I want my array to look like this.

  • Online -> ID 1
  • Offline -> ID 2
  • Absent -> ID 3
  • Logout -> ID 0

Anybody has an Id how I can do this?

Change this:

if(!logout){
    Status* newStatus = [NSEntityDescription insertNewObjectForEntityForName:@"Statussen" inManagedObjectContext:context];
    newStatus.cs_id = [NSNumber numberWithInt:0];
    newStatus.cs_name = @"Logout";
    [_arrStatus addObject:newStatus];
} 

To this:

if(!logout){
    Status* newStatus = [NSEntityDescription insertNewObjectForEntityForName:@"Statussen" inManagedObjectContext:context];
    newStatus.cs_id = [NSNumber numberWithInt:0];
    newStatus.cs_name = @"Logout";
    [_arrStatus insertObject:newStatus atIndex:0];
} 

To put the log in the front of the array. Or if you need to sort the array you can use something like this:

NSArray *sortedArray = [_arrStatus sortedArrayUsingComparator: ^(id obj1, id obj2) {
    return (NSComparisonResult)[(Status*)obj1.cs_id compare:(Status*)obj2.cs_id];
}];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM