如何为本地创建的对象分配唯一ID

时间:2014-06-18 17:06:11

标签: ios objective-c core-data nsmanagedobject

我计划稍后使用CloudKit,据我所知,它可以自动在云中分配唯一的ObjectID,但出于编辑和更新目的,我想自己创建这些唯一ID并在CoreData中设置属性。 / p>

您能否建议在我的代码中创建唯一ObjectID的正确方法?

我到目前为止这段代码:

+ (CoreDataStatus)saveNewItem:(NSString *)text date:(NSDate *)date priority:(NSUInteger)priority
{
    NSManagedObjectContext *context = [self getContext];
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    __block NSError *error;

    [context performBlockAndWait:^{
        Task *newTask = [NSEntityDescription insertNewObjectForEntityForName:@"Task" inManagedObjectContext:context];
        newTask.due = date;
        newTask.text = text;
        newTask.priority = [NSNumber numberWithInteger:priority];

        // push to parent
        if (![context save:&error])
        {
            // handle error
        }

        // save parent to disk asynchronously
        [appDelegate.managedObjectContext performBlockAndWait:^{
            NSError *error;
            if (![appDelegate.managedObjectContext save:&error])
            {
                // handle error
            }
        }];
    }];

    if (!error) {
        return Success;
    } else {
        return Error;
    }
}

0 个答案:

没有答案