【问题标题】:How to get ObjectId correctly in CoreData IOS?如何在 CoreData IOS 中正确获取 ObjectId?
【发布时间】:2014-11-06 04:21:42
【问题描述】:

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

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

通过它我可以检索 id 即 4.But 有时它以 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];
}

请帮帮我。

【问题讨论】:

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


    【解决方案1】:

    您不应该为此使用ObjectID。如果您希望使用主键,您确实应该创建自己的主键并从中获取。

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

    【讨论】:

      【解决方案2】:

      要获得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);
      }
      

      【讨论】:

        猜你喜欢
        • 2020-07-20
        • 1970-01-01
        • 1970-01-01
        • 2017-01-24
        • 2019-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多