过滤NSFetchedResultsController为nil值? [英] Filter NSFetchedResultsController for nil value?

查看:181
本文介绍了过滤NSFetchedResultsController为nil值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 NSFetchedResultsController ,它从 NSManagedObjectContext 中获取对象。



这些对象具有 lastOpened 属性,最初为 nil

我想让我的 UITableView 显示最多的列表。最近打开的对象,这可以通过向 NSFetchRequest 添加 NSSortDescriptor 来实现。



问题:



我不想显示从来没有研究过。 ( lastOpened == nil )我可以通过相同的 NSFetchRequest 是否有更好的方法来过滤数据?



感谢。

解决方案

当然。您要查找的是 NSPredicate 。基本上,它允许你指定一个或多个条件,你想要获取的对象满足,然后只获取匹配这些条件的对象。



构建谓词是一个有点棘手但是,您可能需要查看谓词格式字符串语法指南。 对于你的特殊情况,它甚至更复杂,因为我不知道有一个表示nil值的谓词条款。但是,你可以通过使用一些远在过去的日期:

   NSPredicate * predicate = [NSPredicate predicateWithFormat:@lastOpened>%@,
[NSDate dateWithTimeIntervalSince1970:0]];



您可以直接在谓词中检查nil:

  NSPredicate * predicate = [NSPredicate predicateWithFormat:@ lastOpened!= nil];  

这将创建一个谓词,只允许设置日期的对象1970)。然后,您可以在执行前将谓词添加到抓取请求中:

  //假设您有一些几乎就绪的NSFetchRequest * request:
[request setPredicate:predicate];


I have a NSFetchedResultsController which is fetching objects from a NSManagedObjectContext.

These objects have a lastOpened property, which is initially nil and is only set when they are viewed.

I want my UITableView to display a list of the most recently opened objects, which I can do by adding a NSSortDescriptor to the NSFetchRequest.

Question:

I don't want to display the objects which have never been studied. (lastOpened == nil) Can I sort this via the same NSFetchRequest? Is there a better way to filter the data?

Thanks.

解决方案

Absolutely. What you're looking for is an NSPredicate. Basically, it allows you to specify one or more conditions that you want your fetched objects to meet, then only fetches objects that match those conditions.

Building predicates is a slightly tricky proposition, however - you might want to take a look at the Predicate Format String Syntax guide to get started. For your particular case, it's even trickier since I'm not sure there's a representation for the nil value in predicate terms. You can get around this, however, by using some date in the distant past:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"lastOpened > %@",
                          [NSDate dateWithTimeIntervalSince1970:0]];

You can just check against nil directly in a predicate:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"lastOpened != nil"];

This creates a predicate that only allows objects with a set date (anything after January 1, 1970) to be returned. You'd then add the predicate to the fetch request before you execute it:

// Assuming you have some almost-ready NSFetchRequest *request:
[request setPredicate:predicate];

这篇关于过滤NSFetchedResultsController为nil值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆