objective-c - 核心数据独特的属性

标签 objective-c iphone cocoa-touch xcode

是否可以使核心数据属性唯一,即没有两个 MyEntity 对象可以具有相同的 myAttribute?

我知道如何以编程方式强制执行此操作,但我希望有一种方法可以使用 xcode 中的图形数据模型编辑器来执行此操作。

我使用的是 iPhone 3.1.2 SDK。

最佳答案

每次我在对象上创建时,我都会执行一个类方法,仅当另一个实体不存在时才创建一个新实体。

+ (TZUser *)userWithUniqueUserId:(NSString *)uniqueUserId inManagedObjectContext:(NSManagedObjectContext *)context
{
    TZUser *user = nil;
    NSFetchRequest *request = [[NSFetchRequest alloc] init];

    request.entity = [NSEntityDescription entityForName:@"TZUser" inManagedObjectContext:context];
    request.predicate = [NSPredicate predicateWithFormat:@"objectId = %@", uniqueUserId];
    NSError *executeFetchError = nil;
    user = [[context executeFetchRequest:request error:&executeFetchError] lastObject];

    if (executeFetchError) {
         NSLog(@"[%@, %@] error looking up user with id: %i with error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), [uniqueUserId intValue], [executeFetchError localizedDescription]);
    } else if (!user) {
        user = [NSEntityDescription insertNewObjectForEntityForName:@"TZUser" 
                                             inManagedObjectContext:context];
    }

    return user;
}

关于objective-c - 核心数据独特的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2239797/

相关文章:

iphone - 如何从 NSManagedObjectContextObjectsDidChangeNotification 中排除属性

iphone - 将 CoreAnimation 导出到视频文件

cocoa-touch - 释放对象会破坏对象吗?

iphone - 滚动以在 UIView 中加载内容

objective-c - 如何安全地将此 double 转换为 int?

ios - 如果任何值为 NULL,CFPropertyListCreateDeepCopy 返回 nil

ios - Objective C NSStream 连接总是被拒绝

objective-c - XCode 构建结果 : why is it so amazingly complex even for a hello world console app?

iPhone 应用程序发送 Facebook 消息或张贴到 friend 的墙上

iphone - 如何让 UITableview 在重新加载时转到页面顶部?