我使用NSSortDescriptor使用firstName对联系人进行排序,但如果名字是nil,则排序错误。
如果我有:
联系人1:Firstname = BAAAA和LastName = XXXXXX
联系人2:Firstname = nil和LastName = AAAAAA
它会是这样的。
1- AAAAAAA
2- BAAAA XXXXXX
所以我需要知道是否存在一个在Firstname和LastName之间建立优先级的解决方案。
如果Firstname ==nil
那么采用LastName
谢谢
答案 0 :(得分:1)
NSSortDescriptor *descriptor1 = [[NSSortDescriptor alloc] initWithKey:@"lastName" ascending:YES];
NSSortDescriptor *descriptor2 = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES];
NSArray *sorted = [contatcs sortedArrayUsingDescriptors:@[descriptor1, descriptor2]];
数组中描述符的顺序决定了优先级。对于核心数据查询,它将类似于
NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Contact" inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
[request setSortDescriptors:@[descriptor1, descriptor2]];
NSError *error;
NSArray *array = [moc executeFetchRequest:request error:&error];
if (array == nil)
{
// Deal with error...
}
答案 1 :(得分:0)
您可以继承NSSortDescriptor
并覆盖compareObject:toObject:
方法:
- (NSComparisonResult)compareObject:(id)object1 toObject:(id)object2 {
NSString *firstName1 = [object1 valueForKey:@"firstName"];
NSString *lastName1 = [object1 valueForKey:@"lastName"];
NSString *firstName2 = [object2 valueForKey:@"firstName"];
NSString *lastName2 = [object2 valueForKey:@"lastName"];
if(firstName1 == nil || firstName2 == nil) {
return [lastName1 compare:lastName2];
}
return [firstName1 compare:firstName2];
}