NSPredicate有20个最后记录

时间:2013-01-28 19:50:24

标签: core-data nspredicate nsfetchrequest

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

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岁,有人可以帮我吗?

2 个答案:

答案 0 :(得分: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];

答案 1 :(得分: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。