开发者

UIPickerView selects entity from managedObjectContext

I'm struggling with a CoreData related problem for a while now:

I have a View-based application with a tabbar in it. The first two tabs are view controllers that display content from my CoreData, the third tab has a UIPickerView, where I can select data. The third and the second view controllers then should select the right entity based on the UIPickerView selection.

To clarify this a little bit more: in my managedobjectcontext I have 16 entities. Based on the UIPickerView selection in ThirdViewCo开发者_如何学编程ntroller I want to use the corresponding entity and update the FirstViewController and SecondViewController.

This should also be a persistent solution, so that the user can quit the application, but the selection from UIPickerView should be stored. Maybe this is something for NSUserDefaults?

Any help would be greatly appreciated!


I am not exactly clear on whether you need to save an entity name or a particular managed object but in both cases the solution is the same: you need to store a reference in the NSUserDefaults.

To store an entity in the user defaults you would just save the entity name as a string. So something like:

  [[NSUserDefaults standardUserDefaults] setValue:entityNameString forKey:@"currentlySelectedEntity"];

... and to retrieve it:

  NSString *currentEntity=[[[NSUserDefaults standardUserDefaults] valueForKey:@"currentlySelectedEntity"];

If you need to save a reference to a particular managed object, you need to save the managed object ID of the saved object. Saving is very important. Prior to saving the context in which the object was created, the object ID has only a temporary value which will change upon saving. Any reference to object will be lost if you use the temporary value.

To save an object ID:

  NSManagedObject *mo=[NSEntityDescription insertNewObjectForEntityForName:@"TestEntity" inManagedObjectContext:self.managedObjectContext];
  //... save the context
  NSManagedObjectID *moID=[mo objectID];
  NSURL *moIDURI=[moID URIRepresentation];
  [[NSUserDefaults standardUserDefaults] setValue:moIDURI forKey:@"currentlySelectedTestObject"];

... to retrive it:

  NSURL *uri=[[NSUserDefaults standardUserDefaults] valueForKey:@"currentlySelectedTestObject"];
  NSManagedObjectID *moID=[self.persistentStoreCoordinator managedObjectIDForURIRepresentation:uri];  
  NSManagedObject *mo=[self.managedObjectContext objectRegisteredForID:moID];

(The above code is uncompiled and may contain typos so don't just copy and paste it.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜