0

我正在处理核心数据,我尝试使用最后 20 条记录,setFecthLimit但在这些最后的记录中我想获得未读计数,我使用这个

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Post" inManagedObjectContext:_managedObjectContext];
[request setEntity:entity];
[request setFetchLimit:20];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"isRead = NO OR isRead = NIL"];
[request setPredicate:predicate];                    

NSError *error = nil;
NSMutableArray *records = [[_managedObjectContext
                                            executeFetchRequest:request
                                            error:&error] mutableCopy];

但它总是返回我 20,有人可以帮我吗?

4

2 回答 2

0

一个简单的解决方案是删除谓词。抓取 20 个对象,然后根据谓词过滤它们。

例如:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Post" inManagedObjectContext:_managedObjectContext];
[request setEntity:entity];
[request setFetchLimit:20];                    

NSError *error = nil;
NSArray *records = [_managedObjectContext executeFetchRequest:request
                                                        error:&error];

// do some error checking here...
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"isRead = NO OR isRead = nil"];
// [NSPredicate predicateWithFormat:@"isRead = %@", [NSNumber numberWithBool:NO]];
NSArray *filteredRecords = [records filteredArrayUsingPredicate:predicate];
于 2013-01-28T23:09:56.840 回答
0

我认为您的谓词格式有错字:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Post"]
request.fetchLimit = 20;
request.predicate = [NSPredicate predicateWithFormat:@"(isRead == NO) OR (isRead == NULL)"];
NSSortDescriptor = [...insert your sort descriptor code here...]
request.sortDEscriptos = @[sd];

记住排序,这样你就可以得到最后的 20 个,而不仅仅是随机的 20 个。

于 2013-01-29T20:08:45.053 回答