gpt4 book ai didi

iphone - Core Data 中的自定义访问器方法实现是什么样子的?

转载 作者:行者123 更新时间:2023-12-03 19:05:48 30 4
gpt4 key购买 nike

文档对此非常困惑:

The implementation of accessor methods you write for subclasses of NSManagedObject is typically different from those you write for other classes.

If you do not provide custom instance variables, you retrieve property values from and save values into the internal store using primitive accessor methods. You must ensure that you invoke the relevant access and change notification methods (willAccessValueForKey:, didAccessValueForKey:, willChangeValueForKey:, didChangeValueForKey:, willChangeValueForKey:withSetMutation:usingObjects:, and didChangeValueForKey:withSetMutation:usingObjects:). NSManagedObject disables automatic key-value observing (KVO, see Key-Value Observing Programming Guide) change notifications, and the primitive accessor methods do not invoke the access and change notification methods.

In accessor methods for properties that are not defined in the entity model, you can either enable automatic change notifications or invoke the appropriate change notification methods.

是否有任何示例可以展示它们的外观?

最佳答案

如果进入数据模型编辑器,选择实体属性,然后选择“将方法实现复制到剪贴板”。它将为您生成访问器。以下是 Core Data 模板项目中默认“timeStamp”属性的访问器:

- (NSDate *)timeStamp 
{
NSDate * tmpValue;

[self willAccessValueForKey:@"timeStamp"];
tmpValue = [self primitiveValueForKey:@"timeStamp"];
[self didAccessValueForKey:@"timeStamp"];

return tmpValue;
}

- (void)setTimeStamp:(NSDate *)value
{
[self willChangeValueForKey:@"timeStamp"];
[self setPrimitiveValue:value forKey:@"timeStamp"];
[self didChangeValueForKey:@"timeStamp"];
}

这里的基本思想是,您必须使用 willChange...didChange... 调用将任何原始值更改括起来,以便上下文知道其中存在某些内容被改变的过程。

您通常不必摆弄自己的访问器,除非设置属性有副作用。

关于iphone - Core Data 中的自定义访问器方法实现是什么样子的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3022625/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com