我想对用户创建的联系人进行排序,其中联系人有大杂烩的数据。某些联系人可能会填写所有字段或属性,例如lastName,firstName,company,phone,email,而其他人可能只有一个名字或只是一封电子邮件或只是一家公司。
使用NSSort描述符的常用方法是创建一个NSArray,其中数组中的第一个sortDescriptors优先于每个连续一个断开的连接。从而:
NSSortDescriptor *last =[[NSSortDescriptor alloc]initWithKey:@"lastname" ascending:YES];
NSSortDescriptor *first =[[NSSortDescriptor alloc]initWithKey:@"firstname" ascending:YES];
NSSortDescriptor *company =[[NSSortDescriptor alloc]initWithKey:@"company" ascending:YES];
NSSortDescriptor *email =[[NSSortDescriptor alloc]initWithKey:@"email" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObjects:last, first, company,email, nil]];
应用于
Allen,Joe,microsoft,[email protected]|Allen,Zack,google,nil|Smith,Tom,Apple,nil
会给你:
Allen, Joe
Allen, Zack
Smith, Tom
看起来很好。
但是,如果您的数据如下:
Allen,Joe,nil,[email protected]|nil,Zack,nil,[email protected]|nil,nil,nil,raj@gmailcom|nil,nil,cloudflare,nil
以上会给你:
cloudflare
[email protected]
Zack
Allen, Joe
这是一团糟。
在第二种情况下,如果只是通过电子邮件排序的电子邮件,如果只有公司按公司排序,后跟姓氏,后跟名字,我想要更有意义的事情
[email protected]
cloudflare
Allen, Joe
Zack
或者,甚至,他们按顺序排列的任何字段
Allen, Joe
cloudflare
[email protected]
Zack
有没有办法实现这个目标?苹果如何与他们的联系人一起做?
谢谢你的任何建议
而不是使用初始化您的排序描述符
initWithKey:ascending:
你可以用
initWithKey:ascending:comparator:
在比较器块中
^NSComparisonResult(id obj1, id obj2) {…}
您可以显式检查nil
对象,并根据需要设置比较结果。
我没有检查这个,但它应该工作。