Reputation: 2941
I'm working on an app where I have Post objects, each Post can have many Entities (mentions, hashtags and links), each Entity have one Post. I have one main class for Entity, then I have three subclasses.
Mention : Entity
My mention class have the following properties:
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * userId;
I now want to create a NSPredicate
that finds all Posts that are mentioning a certain User and userId
, and I'm not sure how I should do that.
I have tried some things like this:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY mentions.userId like %@", [Session currentUser].userId];
// That doesn't work since Post(s) have many entities and not Mention(s).
// I have also tried something like this:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY entities.mentions.userId like %@", [Session currentUser].userId];
// And that didn't work either.
Any ideas on how I best should find all posts that are mentioning a certain user with a specific userId?
Upvotes: 0
Views: 295
Reputation: 80271
Inheritance is there so you do not have to code equal attributes twice. Otherwise, managed objects with parent objects are just like other managed objects.
Therefore, you should give your posts three relationships:
Post
hashes Hash
mentions Mention
links Link
Then your problem becomes trivial:
[NSPredicate predicateWithFormat:@"ANY hashes.userID = %@", _currentUser.userID];
Like does not make sense, as userID
is presumably unique, and LIKE
is much more expensive than simple equivalence.
If you want just one to-many relationship to one class of entity you will have to include another attribute in Entity
, e.g. an NSNumber
, to indicate what type it is. The predicate would then be as follows, assuming you use an enum
to make the number types more readable:
[NSPredicate predicateWithFormat:
@"ANY (entity.type == %@ && entity.userID == %@)",
@(EntityTypeMention), _currentUser.userID];
Upvotes: 1