Core data: can NSFetchedResultsController fetch tw

2020-02-19 08:13发布

I am working on an iPhone app, and in a particular view I need to load two different entities: One that will populate a UITableView, and another that will populate a UITextView.

Is it possible to fetch both properties using a single NSFetchedResultsController?

Or do I need to use two different NSFetchedResultsControllers?

Any ideas on how to best approach this problem?

4条回答
一夜七次
2楼-- · 2020-02-19 08:32

Each fetch request has only one entity and each fetched results controller has only one fetch. Therefore, you need separate controllers for each entity.

If you think about it, how would you make a predicate to fetch two logically separate entities?

You probably don't need two fetches at all. In most cases, you can fetch the entities that populate the table and then use a relationship for the entity of the selected row to populate something like a text view.

查看更多
成全新的幸福
3楼-- · 2020-02-19 08:35
The quick answer is NO. But I found a creative answer.

In your tableViewController, make a search bar with how many scopes you have.

When different scope is selected, you can fetch different entities!

This works because I made an app like this!

Users would have easier time separating the two different data too!

查看更多
姐就是有狂的资本
4楼-- · 2020-02-19 08:38

Best solution would be to refactor your Model and see if your 2 entities have something in common. You can make an abstract entity for the intersecting stuff, then inherit your 2 entities out of that. Perform the fetch on the abstract entity, and your fetch results controller should return mixed results.

查看更多
Luminary・发光体
5楼-- · 2020-02-19 08:50

As TechZen stated, the answer is no.

However, you can monitor the saves of the NSManagedObjectContext yourself and react to those saves. If you really do need to watch more than one entity (something that is far more common on the iPad than the iPhone) then add a NSNotification observer on the NSManagedObjectContextDidSaveNotification and look at the -userInfo of the NSNotification that comes back. You can then run predicates on against the results to determine if you need to update your display. That is what the NSFetchedResultsController is doing under the covers.

查看更多
登录 后发表回答