简体   繁体   中英

iPhone - Core Data Model Design Question

I'm auditing the iTunesU iPhone development course by Stanford, and am trying to wrap my head around using Core Data.

Essentially, the application has two tabs that utilize Core Data: 1) Favorite Photos - This is a list of Locations (from Flickr) that the user has selected to "favorite" a photo for. (If there are no photos "favorited" in a given location it is removed from this list). 2) Recent Photos - This is a list of photos most recently viewed by the user.

My initial thought was to use two entities: Photo and Location, where Photo would have the a relationship "whereTaken" that would be a Location, and Location would have the inverse relationship "photos" to contain all Photo objects from that Location.

However, with this model, I get a little confused on how to keep track of whether or not a given Location has any "favorited" photos left. The assignment suggested to keep an attribute in the Location entity to specify whether or not there are any "favorited" photos in that location.

So -- here are my questions:

  1. Would it be better to create separate entities for "FavoritePhoto" and "RecentPhoto" rather than just "Photo"?
  2. If not, is it suggested (or possible) to keep a subset of photos (only the "favorited" ones in the inverse relationship) in Location?
  3. Or, do I need to iterate on the NSSet of Photo objects every time I remove a "favorited" photo to see if there are any other "favorited" photos left? Or, perhaps keep a count of favorited photos as an attribute in Location?

Maybe, I'm going about this completely wrong -- either way, I'd appreciate any kind of advice, general or specific, regarding designing a Core Data model in this case.

Thank you very much for your time and help!

You should read up a bit on NSPredicate. You can attach this to a fetch request to filter the photos you wish to retrieve. Creating two different Photo entities is most likely a mistake. You might want to add a BOOL attribute "isFavorite" to the Photo entity. Then, when fetching the photos, you would use something like:

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

You can also make slightly more complex predicates to filter for both favorite status and location.

NSPredicate Programming Guide

You can create a fetched Property in the Location entity and have it only fetch the 'favorited' photos with the appropriate predicate.

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM