【问题标题】:CoreData modeling relationship reviewCoreData建模关系回顾
【发布时间】:2026-01-18 16:55:02
【问题描述】:

我有一个包含标准用户凭据的 AccountCredential 对象,然后是另一个包含其中几个 AccountCredential 对象的对象。当我在 CoreData 中对此进行建模时,我想知道 AccountCredential 是否需要为其拥有的每个实例都建立一个返回 Account 的关系链接。

我会在 CoreData 中这样设置吗:

@interface Account :  NSManagedObject  
{
}

@property (nonatomic, retain) AccountCredential * twitterAccountCred;
@property (nonatomic, retain) AccountCredential * facebookAccountCred;

@end


@interface AccountCredential :  NSManagedObject  
{
}

@property (nonatomic, retain) NSString * password;
@property (nonatomic, retain) NSString * username; // encrypted
@property (nonatomic, retain) Account * account1;
@property (nonatomic, retain) Account * account2;

@end

或者,Account 有对 AccountCredential 的引用并且没有从 AccountCredential 到 Account 的关系链接就足够了吗?

AccountCredential 没有理由知道它用于“帐户”界面中的两种类型的帐户,因此我将其视为单向参考。我知道 CoreData 喜欢关系是双向的,但我很好奇这在模型中是否必要。

非 CoreData 关系如下所示:

@interface AccountCredential : NSObject {
    NSString *username;
    NSString *password; //encrypted
}
@end

@interface Account : NSObject {
    AccountCredential       *twitterAccountCred;
    AccountCredential       *facebookAccountCred;
}
@end

【问题讨论】:

    标签: objective-c core-data


    【解决方案1】:

    如果您构建它,Xcode 可能会警告您不存在反向关系。当你有反向关系时,CoreData 真的很喜欢它(我不记得推理但当你真正考虑它时它确实有道理)。

    【讨论】:

    • Core Data 使用反向关系信息来确保对象图在发生变化时的一致性。但我想知道我是否不必做反比关系......如果是这样,还有没有办法抑制这个警告?