在不同的ViewControllers之间创建关系

时间:2014-01-16 11:17:53

标签: ios objective-c

我的实体之间有以下关系。 enter image description here

我有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

1 个答案:

答案 0 :(得分:0)

您需要为用户提供一些方法来选择与歌曲相关联的播放列表。 2个一般选项:

  1. 选择播放列表以查看和编辑其中包含的歌曲(以便将播放列表从第一个控制器传递到第二个控制器)。
  2. 显示歌曲详细信息并有一个显示播放列表选择器的按钮(可以是选择器视图或表格视图)。这使用委托将播放列表返回给歌曲控制器。

  3. 获得playlistsong托管对象后,请使用:

    [playlist addSongsObject:song];
    

    在保存上下文之前(将更新两个对象关系,因为它们是相反的)。