Reputation: 7149
IN a bit of a pickle. I am implementing a CoreData solution and I have two entities, Site and Post. Now Site has many Posts as Post belongs to one Site, as reflected in the model diagram.
In my entity code I have :
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * url;
@property (nonatomic, retain) NSSet* post;
@property (nonatomic, retain) NSSet* tag;
...
@interface Site (CoreDataGeneratedAccessors)
- (void)addPostObject:(Post *)value;
- (void)removePostObject:(Post *)value;
- (void)addPost:(NSSet *)value;
- (void)removePost:(NSSet *)value;
@property (nonatomic, retain) NSDate * date;
@property (nonatomic, retain) NSNumber * views;
@property (nonatomic, retain) NSSet* comment;
@property (nonatomic, retain) Site * site;
...
@interface Post (CoreDataGeneratedAccessors)
- (void)addCommentObject:(Comment *)value;
- (void)removeCommentObject:(Comment *)value;
- (void)addComment:(NSSet *)value;
- (void)removeComment:(NSSet *)value;
- (void)addMediaObject:(Media *)value;
- (void)removeMediaObject:(Media *)value;
- (void)addMedia:(NSSet *)value;
- (void)removeMedia:(NSSet *)value;
@end
My issue is, i need to access a post that belongs to a Site, so i guess I logically need to get an array of all the posts belonging to a user. can someone provide me sample code to do this? Ive been scouring the internet to find sample code but yeah, no luck so far
Upvotes: 0
Views: 480
Reputation: 78393
How are you associating a user with a post in the first place? I don't see any attribute or relationship in your posted code that associates a user... but, for the sake of argument, let's assume that a Post entity has an attribute named user (for this simple example, user is just an NSString that identifies the user by name).
NSString* user = @"our_username";
NSFetchRequest* request = [[[NSFetchRequest alloc] init] autorelease];
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SELF.user LIKE[cd] %@", user];
[request setEntity:[NSEntityDescription entityForName:@"Post" inManagedObjectContext:someContext]];
[request setPredicate:predicate];
NSError* error = nil;
NSArray* postsForUser = [someContext executeRequest:request error:&error];
if( !postsForUser ) {
// handle error
}
// Will contain all posts by user
NSLog(@"posts: %@", postsForUser);
Upvotes: 1