开发者

iphone - UITableView with list of firstname lastname as in contacts application

I've an application which has an array of contacts. Each object in the array is dictionary which holds first name and last name. In the contacts application on iphone, it shows the users sorting alphabetically. If first name is not available last name is consider while sorting.

How can I do similar sorting. I know how to do sorting based on one field as following:

    NSArray* tempArray = [jsonData objectForKey:@"contacts"];
    NSSortDescriptor *sortDescriptor;
    sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"first_name"
                                                 ascending:YES] autorelease];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    contactsArray = [[NSArray alloc] initWithArray:[tempArray sortedArrayUsing开发者_开发技巧Descriptors:sortDescriptors]];

How can I sort the array of contacts based on first name or last name availability.


For your reference:

{
    ...
    NSInteger order = (NSInteger)ABPersonGetSortOrdering();
        if (order == kABPersonSortByFirstName) 
        {
            int firstNameFirst = YES;
            [self.contactList sortUsingFunction:alphabeticPersonNameSort context:&firstNameFirst];
        }
        else 
        {
            int firstNameFirst = NO;
            [self.contactList sortUsingFunction:alphabeticPersonNameSort context:&firstNameFirst];
        }
    ...
}

static NSInteger alphabeticPersonNameSort(NSArray *obj1, NSArray *obj2, void *firstNameFirst)
{
    if ((*(int *) firstNameFirst) == NO)
    {
        // FullName = LastName, FirstName
            // FirstName: [obj1 objectAtIndex:0]
            // LastName: [obj1 objectAtIndex:1]
        NSString *fullName1 = [NSString stringWithFormat:@"%@, @%", [obj1 objectAtIndex:1], [obj1 objectAtIndex:0]];
        NSString *fullName2 = [NSString stringWithFormat:@"%@, @%", [obj2 objectAtIndex:1], [obj2 objectAtIndex:0]];
        return [fullName1 localizedCaseInsensitiveCompare:fullName2];
    }
    else
    {
        // Only sorted by using firstName

        NSString *fullName1 = [NSString stringWithFormat:@"%@", [obj1 objectAtIndex:0]];
        NSString *fullName2 = [NSString stringWithFormat:@"%@", [obj2 objectAtIndex:0]];
        return [fullName1 localizedCaseInsensitiveCompare:fullName2];
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜