2014-01-16 224 views
0

我有一個ViewController與保存在NSMutableArray中的播放列表。我使用Singleton將所選對象傳遞給SecondViewController。創建實體之間的關係

optionsSingle.selectedRowNow = [devices objectAtIndex:indexPath.row]; 

在SecondViewController中,我添加了歌曲。我如何關聯傳遞給SecondViewController的optionsSingle.selectedRowNow與保存的歌曲?我會很感激代碼片段/示例,因爲我一直在努力掙扎幾個小時,並且一直沒能在互聯網上找到有用的東西。

歌曲添加方法:

NSManagedObjectContext *context = 
[appDelegate managedObjectContext]; 
NSManagedObject *newManagedObject; 
newManagedObject = (Songs*)[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"]; 

實體

songs.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.h

@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

請注意,您關係的命名是「非常規」,可能是您混淆的原因(請比較我的建議以迴應您之前的問題:http://stackoverflow.com/a/21149021/1187415)。從「歌曲」到「播放列表」的關係應該被稱爲「列表」或「播放列表」,但不是「歌曲」。從「播放列表」到「歌曲」的關係應該被稱爲「歌曲」,而不是「列表」。 –

回答

0
[optionsSingle.selectedRowNow addListObject:newManagedObject]; 

這會從'singleton'獲取播放列表並將關係添加到歌曲(追加到當前關係中的任何歌曲)。

+1

完成之後,它將不會保存到數據庫。你需要在你的NSManagedObjectContext實例上調用'save:'。 –

+0

我爲什麼不能使用addSongsObject?我輸入了2個實體? – user3195388

+0

我得到了錯誤的方法名稱。你的名字真的很糟糕......播放列表實體應該有歌曲,而歌曲實體應該有播放列表作爲關係名稱。 – Wain