开发者

How to retrieve stored reference to an NSManagedObject subclass?

I have a NSManagedObject subclass named Tour. I stored the reference to it using this code:

    prefs = [NSUserDefaults standardUserDefaults];
NSURL *myURL = [[myTour objectID] URIRepresentation];
 NSData *uriData = [NSKeyedArchiver archivedDataWithRootObject:myURL];
 [prefs setObject:uriData forKey:@"tour"];

Now I want to retrieve it. I tried using:

NSData *myData = [prefs objectForKey:@"tour"];
  NSURL *myURL = [NSKeyedUnarchiver unarchiveObjectWithData:myData];

  TourAppDelegate *appDelegate = (TourAppDelegate *)[[UIApplication sharedApplication] delegate];

  NSManagedObjectID *myID = [appDelegate.persistentStoreCoordinator managedObjectIDForURIRepresentation:myURL];

  if (m开发者_开发问答yID)
  {
  Tour *tempObject = [appDelegate.managedObjectContext objectWithID:myID]; //WARNING
  tour = tempObject;
  }

  if (tour) //instruction...

But it's giving me this warning "Incompatible Objective-c types. Initializing 'struct NSManagedObject *', expected 'struct Tour *'

Plus, when executing, it's giving me this: Terminating app due to uncaught exception 'NSObjectInaccessibleException', reason: 'CoreData could not fulfill a fault for '0x5001eb0

How can I solve this?


Regarding the warning, did you try to force type casting?

Tour *tempObject = (Tour *) [appDelegate.managedObjectContext objectWithID:myID];

The problem related to NSObjectInaccessibleException is solved in the link St3fan posted :)

PS: Remember that a subclass of nsmanagedobject is still a nsmanagedobject!


This is a great article about storing and retrieving references to objects.

http://cocoawithlove.com/2008/08/safely-fetching-nsmanagedobject-by-uri.html


Looks like the URI you have is not registered in the context.

From the docs:

If the object is not registered in the context, it may be fetched or returned as a fault. This method always returns an object. The data in the persistent store represented by objectID is assumed to exist—if it does not, the returned object throws an exception when you access any property (that is, when the fault is fired). The benefit of this behavior is that it allows you to create and use faults, then create the underlying rows later or in a separate context.

objectRegisteredForID: will return nil if you want to gracefully fail from this condition

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜