【问题标题】:property as NSManagedObject in view controller for a "current NSManagedObject"属性作为“当前 NSManagedObject”的视图控制器中的 NSManagedObject
【发布时间】:2012-08-29 18:36:29
【问题描述】:

我有兴趣在视图控制器中将属性设置为 NSManagedObject 的子类,比如 Person,它将指定 person 的实例,以便我能够使用控制器中的方法进行更新。我可以这样做吗?

// Viewcontroller.h

@implementation

@property (nonatomic, retain) Person* currentPerson;

@end

// ViewController.m

@implementation

@dynamic currentPerson;

-(void) doSomethingToCurrentPerson {
    currentPerson.SomeAtrribute=somevalue;
}  

@end

如果这不是一个有效的方法,也可以设置一个唯一标识符,然后将 CurrentPersonUniqueID 存储为属性并使用 KVC。有没有办法让我发布的工作内容与我发布的内容一致,或者我最好使用更接近 KVC 方法的方法,或者完全不同的方法?

【问题讨论】:

    标签: objective-c core-data properties nsmanagedobject


    【解决方案1】:

    在您将 @dynamic 替换为 @synthesize 之前,此代码将不起作用。 @dynamic 告诉编译器 -setCurrentPerson:-currentPerson 在其他地方实现,事实并非如此。

    所以@synthesize currentPerson 将自动创建currentPerson 的getter/setter。这与PersonNSManagedObject 的事实没有任何关系。

    另外,要么你不能用这个名字直接访问currentPerson,你必须使用它的getter:

    self.currentPerson.attribute = something;
    // or
    [self currentPerson].attribute = something;
    

    正确代码:

    // Viewcontroller.h
    @implementation    
    @property (nonatomic, retain) Person* currentPerson;
    @end
    
    // ViewController.m
    @implementation
    @synthesize currentPerson;
    
    -(void) doSomethingToCurrentPerson {
        self.currentPerson.SomeAtrribute = somevalue;
    }
    
    @end
    

    【讨论】:

    • @synthesize 对于最新的编译器来说不是必需的......它假定
    • 另外,我更喜欢使用访问器:self.currentPerson,但如果您添加了@synthesize currentPerson = _currentPerson,您可以将人员作为ivar访问:即_currentPerson跨度>
    • 我可以像 NSObject 子类一样将属性更改为 (nonatomic, strong) 吗?
    • @nielsbot:根据the objective-c docIf you do not specify either @synthesize or @dynamic for a [...] property, you must provide a getter and setter [...].。过时了吗?
    • 我明白了。在 ARC 之前我从未使用过 xCode,所以我只知道它非常强大。当我学习 CoreData 时,我看到一些(保留)弹出,我只是使用它,因为我在代码中看到它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-13
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    • 1970-01-01
    相关资源
    最近更新 更多