带有比较器的 NSSortDescriptor 改变了获取与初始加载时的行为
我对 NSSortDescriptor 的行为感到非常奇怪。让我们从我的代码开始:
NSSortDescriptor *nameExists = [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES comparator:^(id obj1, id obj2){
if ( ([obj1 isEqualToString:@""] || [obj1 isKindOfClass:[NSNull class]] || obj1 == nil) && ![obj2 isEqualToString:@""]){
return NSOrderedDescending;
}
else if ( ![obj1 isEqualToString:@""] && ([obj2 isEqualToString:@""] || [obj2 isKindOfClass:[NSNull class]] || obj2 == nil) ){
return NSOrderedAscending;
}
return NSOrderedSame;
}];
这是排序描述符,我用它来按具有名称字段和不具有名称字段的用户对数据库中的用户进行排序。因此,如果您有一个包含 20 人的用户列表,其中 5 人没有名字,但 15 人有名字,则有名字的 15 人将排在没有名字的人之前。这与按升序对字符串字段进行排序的通常行为形成鲜明对比,后者会在非空白字段之前显示带有空白字段的条目。
当我第一次加载视图时,此排序描述符恢复为默认行为 - 空白字段位于完整字段之前,就好像我的比较器不存在一样。
但是,如果我将新条目拉入核心数据,我的 NSFetchedResultsController 会根据我的比较器正确加载条目。
我的直觉告诉我,我的方块的放置有问题。我把它放在视图的 init 方法中。但是,我将其更改为 loadView 方法,并且该行为仍然存在。
有谁知道发生了什么事吗?
I'm getting really bizarre behavior with an NSSortDescriptor. Let's start with my code:
NSSortDescriptor *nameExists = [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES comparator:^(id obj1, id obj2){
if ( ([obj1 isEqualToString:@""] || [obj1 isKindOfClass:[NSNull class]] || obj1 == nil) && ![obj2 isEqualToString:@""]){
return NSOrderedDescending;
}
else if ( ![obj1 isEqualToString:@""] && ([obj2 isEqualToString:@""] || [obj2 isKindOfClass:[NSNull class]] || obj2 == nil) ){
return NSOrderedAscending;
}
return NSOrderedSame;
}];
This is the sort descriptor that I use to order the users in my database by those who have name fields and those who do not. So, if you had a user list of 20 people, and 5 people didn't have first names, but 15 did, the 15 with names would be sorted before those without. This is in start contrast to the usual behavior of sorting a string field as Ascending, which would display the entries with the blank fields before the non-blank fields.
When I first load the view, this sort descriptor reverts to the default behavior - with the blank fields before the full fields, as if my Comparator were not there.
However, if I pull new entries into Core Data, my NSFetchedResultsController loads the entries properly, and according to my comparator.
My gut told me that there is something wrong with the placement of my block. I have it in the init method of the view. However, I changed it to the loadView method and the behavior persisted.
Does anyone have any idea what is going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论