开发者

How to Fetch only Some Objects Matching a Bool Attribute

Every time I fetch objects from the database I get all objects. Now, I have to fetch and show in a table view only some of the objects stored in the database.

To do this, I've thought to add a new attribute in my entity, a BOOL attribute so I can fetch only objects that have this attribute's value equal to YES or NO depending situations.

Is it possible to do something like this?

I've found the -setPropertiesToFetch: method of NSFetchReq开发者_开发技巧uest class that can be useful but I don't know if I can use it to see the different value of a BOOL.


It sounds like you just want to use a predicate. The NSPredicate Class Reference gives a good idea of how to use them. Basically, it adds a filter to your results. For example, let's say you have a core data object with an attribute myBool which is a BOOL (but stored as NSNumber, of course). To filter your results based on that, you would use something like this

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"myBool == %@", [NSNumber numberWithBool:YES]];
[fetchRequest setPredicate:predicate];

then continue as normal. This will return just the results that have the myBool value as YES.

That being said, if you are using the request to simply populate a tableView, you might be better off using the NSFetchedResultsController. A great tutorial on how to implement it can be found here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜