【问题标题】:Create relationship between to entities创建与实体之间的关系
【发布时间】:2014-01-17 05:12:58
【问题描述】:

我有一个带有播放列表的 ViewController,它保存在 NSMutableArray 中。我使用 Singleton 将所选对象传递给 SecondViewController。

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

在 SecondViewController 中,我添加了歌曲。如何将传递给 SecondViewController 的 optionsSingle.selectedRowNow 与保存的歌曲相关联?我会很感激使用代码 sn-p/sample,因为我已经为此苦苦挣扎了几个小时,并且无法在互联网上找到有用的东西。

添加歌曲方法:

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"];

实体

歌曲.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

播放列表.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

【问题讨论】:

  • 请注意,您对关系的命名是“非常规的”,可能是您感到困惑的原因(在此处比较我对您之前的问题的建议:stackoverflow.com/a/21149021/1187415)。从“歌曲”到“播放列表”的关系应该称为“列表”或“播放列表”,而不是“歌曲”。从“播放列表”到“歌曲”的关系应该称为“歌曲”,而不是“列表”。

标签: ios objective-c core-data


【解决方案1】:
[optionsSingle.selectedRowNow addListObject:newManagedObject];

这会从“单例”中获取播放列表并将关系添加到歌曲中(附加到当前关系中的任何歌曲)。

【讨论】:

  • 完成此操作后,它还不会保存到数据库中。您需要在您的 NSManagedObjectContext 实例上调用 save:
  • 为什么我不能使用 addSongsObject?我已经导入了 2 个实体?
  • 我弄错了方法名。你的名字真的很糟糕......Playlist实体应该有songsSong实体应该有playlists作为关系名称。
猜你喜欢
  • 2011-12-22
  • 1970-01-01
  • 1970-01-01
  • 2013-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多