我的实体之间有以下关系。
我有2个ViewControllers。 1添加播放列表的位置和添加歌曲的1。我的问题是,歌曲ViewController如何知道将歌曲关联到哪个播放列表并创建与该确切播放列表的关系?
PlaylistViewController.m(这是我保存播放列表的地方)
-(void)saveTap:(id)sender{
Playlists *newManagedObject = (Playlists*)[NSEntityDescription insertNewObjectForEntityForName:@"Playlists" inManagedObjectContext:_managedObjectContext];
[newManagedObject setValue:self.textfield.text forKey:@"playlistName"];
// Save the context.
NSError *error = nil;
if (![_managedObjectContext save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
[self fetchDevices];
}
SongsViewController.m(这是保存歌曲的地方)
-(IBAction)songsDone:(id)sender{
AppDelegate *appDelegate =
[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
[appDelegate managedObjectContext];
NSManagedObject *newManagedObject;
newManagedObject = [NSEntityDescription
insertNewObjectForEntityForName:@"Songs"
inManagedObjectContext:context];
NSDate *today= [NSDate date];
[newManagedObject setValue:video.author forKey:@"author"];
[newManagedObject setValue:video.videoid forKey:@"link"];
[newManagedObject setValue:video.title forKey:@"songName"];
[newManagedObject setValue:today forKey:@"created"];
// Save the context.
NSError *error = nil;
if (![_managedObjectContext save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
Song.h(实体)
@class Playlists;
@interface Songs : NSManagedObject
@property (nonatomic, retain) NSString * author;
@property (nonatomic, retain) NSDate * created;
@property (nonatomic, retain) NSString * link;
@property (nonatomic, retain) NSString * songName;
@property (nonatomic, retain) NSSet *songs;
@end
@interface Songs (CoreDataGeneratedAccessors)
- (void)addSongsObject:(Playlists *)value;
- (void)removeSongsObject:(Playlists *)value;
- (void)addSongs:(NSSet *)values;
- (void)removeSongs:(NSSet *)values;
@end
Playlists.m(实体)
@class Songs;
@interface Playlists : NSManagedObject
@property (nonatomic, retain) NSString * playlistName;
@property (nonatomic, retain) NSSet *list;
@end
@interface Playlists (CoreDataGeneratedAccessors)
- (void)addListObject:(Songs *)value;
- (void)removeListObject:(Songs *)value;
- (void)addList:(NSSet *)values;
- (void)removeList:(NSSet *)values;
@end
答案 0 :(得分:0)
您需要为用户提供一些方法来选择与歌曲相关联的播放列表。 2个一般选项:
获得playlist
和song
托管对象后,请使用:
[playlist addSongsObject:song];
在保存上下文之前(将更新两个对象关系,因为它们是相反的)。