【发布时间】:2014-01-16 19:51:51
【问题描述】:
我的实体之间有以下关系。
我有 2 个视图控制器。 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
【问题讨论】:
-
我不是在问如何在视图控制器之间传递数据。我在问我如何通过使用关系将歌曲与播放列表相关联,而无需像 SQL 中那样具有自动增量 ID。
标签: ios objective-c