如何在CoreData IOS中正确获取ObjectId?

时间:2014-09-12 04:17:32

标签: ios objective-c core-data ios7 nsmanagedobjectid

我正在尝试使用CoreData ObjectId存储我的唯一记录。有时我成功以这种格式获取ObjectID

<x-coredata://FC004E6F-F3D6-420E-871E-3E281571FB8B/Register/p4>

通过它我可以检索id,即4.但有时它以ObjectId格式返回

<x-coredata:///Playlist/tC481615F-4ABA-4CDA-B703-D1E6303B455D3>

即NSTemporaryObjectID_Default非常烦人。我从我的IOS模拟器清理我的项目,清理Xcode但它运行不正常。

这是获取对象ID的代码:

-(IBAction)TestButton:(id)sender
{
    appObject=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    NSManagedObjectContext *context =[appObject managedObjectContext];
    NSManagedObject *playlistContact;
    NSManagedObjectID *moID = [playlistContact objectID];
    NSString *aString = [[moID URIRepresentation] absoluteString];
    NSArray *theComponents = [aString componentsSeparatedByString:@"/p"];
    NSInteger theZpk = [[theComponents lastObject] intValue];
    playlistId=[NSString stringWithFormat:@"%ld",(long)theZpk];
}

请帮帮我。

2 个答案:

答案 0 :(得分:3)

您不应该使用ObjectID。如果你想使用主键,你真的应该创建自己的主键并取而代之。

ObjectID可以并且会在几种不同的情况下改变你,导致许多问题。它旨在在应用程序的一个生命周期中在应用程序中使用。不建议在整个生命周期中使用它。

答案 1 :(得分:1)

objectID使用:

-(NSManagedObject *)existingObjectWithID:(NSManagedObjectID *)objectID
                               error:(NSError **)error

要获得永久objectID使用obtainPermanentIDsForObjects,例如:

NSManagedObject *contact = [NSEntityDescription insertNewObjectForEntityForName:self.entityName inManagedObjectContext:context];
NSError *error = nil;
if (![context obtainPermanentIDsForObjects:
      @[contact] error:&error]) {
    NSLog(@"Couldn't obtain a permanent ID for object %@",
          error);
}
相关问题