开发者

Using a UIPickerView to make a CoreData Relationship

开发者 https://www.devze.com 2023-01-01 11:26 出处:网络
Okay, so I have a fairly simple application set up. I have two different CoreData Entities, Games and Platforms, each have one attribute: name, and they have a one-to-many relationship between them.

Okay, so I have a fairly simple application set up.

I have two different CoreData Entities, Games and Platforms, each have one attribute: name, and they have a one-to-many relationship between them.

Platforms are populated on the first launch of the application, and will never change as a result of user input.

I'm working on my Add view to let the user add new games to their personal database, and each game should select from a platform. The add view itself is a grouped table view with static custom cells. Tapping the platform cell should advance the user to another view to select the platform.

My thought is that UIPickerView seems like a logical choice for the control, since the Platform list is static, but I'm not sure how to use it with CoreData. Even if I construct a fetch request to get the Platform objects and extract the strings out, how do I go about linking the new Game obj开发者_如何学Cect to the original Platform object?


This only requires a few lines of code, assuming you instantiate your Platforms object just before saving the data, you should do something like:

Platforms *newPlatform = (Platforms *) [NSEntityDescription insertNewObjectForEntityForName:@"Platforms" inManagedObjectContext:self.managedObjectContext];
[newPlatform setValue:@"yourPlatformName" forKey:@"name"];
[newPlatform setValue:yourGameObject forKey:@"games"];

NSError *error;
if (![[self managedObjectContext] save:&error]) {
    // Handle error
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
}

This also automatically update through Core Data yourGameObject.

0

精彩评论

暂无评论...
验证码 换一张
取 消