【问题标题】:Migration from homemade models to core data models: setter/getter issue从自制模型迁移到核心数据模型:setter/getter 问题
【发布时间】:2014-04-28 14:10:37
【问题描述】:

我开始学习如何在我的应用程序中使用 Core Data,我对 NSManagedObject 有一个关于 setter 和 getter 的问题。

在我的旧模型中,我使用这种语法来声明属性:

@interface MyModel : NSObject 
{
    MyAttributeOfClass *_myAttributeOfClass
}

- (void)setMyAttributeOfClass:(MyAttributeOfClass *)anAttributeOfClass;
- (MyAttributeOfClass *)myAttributeOfClass;

我知道,我可以使用 @synthesize 来做这些事情。但是,如果我使用带有公共属性的@synthesize,例如:

@property (nonatomic, strong) MyAttributeOfClass *myAttributeOfClass;

开发人员可以绕过我的设置器并通过这样做直接为myAttributeOfClass 设置一个值:myAttributeOfClass = bar;。我不想允许这种行为,因为我使用 setter 来执行操作。如果不执行此操作,我的班级将无法正常工作。

所以,现在我将旧模型迁移到从 NSManagedObject 子类化的 Core Data 模型。

但是当我从我的数据模型生成类时,属性是这样声明的:

@property (nonatomic, retain) MyAttribute *myAttribute;

因此,开发人员可以在不调用 setter 的情况下为该属性设置值:myAttribute = bar;我想禁止它。

有什么建议吗?

谢谢!

【问题讨论】:

    标签: ios objective-c core-data setter


    【解决方案1】:

    Core Data 托管对象的属性不由实例变量备份。可以使用属性语法设置属性:

    object.myAttribute = bar;
    

    或使用键值编码:

    [object setValue:bar forKey:@"myAttribute"];
    

    在这两种情况下都是setter方法

    -(void)setMyAttribute:(MyAttribute *)value;
    

    被调用。 Setter 和 getter 方法通常是在运行时动态创建的,但是你 可以提供您自己的显式 setter 和/或 getter 方法。

    但是,可以通过调用“原始”访问器方法来绕过设置器:

    [object setPrimitiveValue:bar forKey:@"myAttribute"];
    

    这是自定义 setter 方法将使用的,但任何人都可以调用原始访问器, 没有办法阻止它。

    【讨论】:

    • 哦!我不认为 object.myAtteibute = bar 称为我的自定义设置器。谢谢你的回答!
    【解决方案2】:

    当我想拥有一个私有设置器时,我的方法是在标题中包含它:

    @property (nonatomic, strong, readonly) NSString*  myProperty;
    

    然后在.m文件中添加:

    @interface MyClass ()
    @property (nonatomic, strong) NSString* myProperty;
    @end
    

    该属性在外部是只读的,但通过在实现文件中定义私有类别,该属性在实现内是可读写的。

    【讨论】:

    • 请注意,这仍然允许 setPrimitiveValue 和 setValue:forKey:,但是,就此而言,Objective-C 从来没有真正的私有方法,因为一切都可以通过反射找到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 2018-08-09
    相关资源
    最近更新 更多