具有在 getter 中返回对象副本并在 setter 中保留对象的属性
我在理解属性时遇到问题。 如果我希望属性不被其访问器修改(通过复制返回)并通过引用设置(保留),我应该编写什么样的属性。
例子 :
MyType* theAttribute = MyObject.attribute;
[theAttribute changeSomething]; // Does not have to change the MyObject attribute, working with a copy return
MyType tmpObject = [[MyType alloc] init];
MyObject.attribute = tmpObject; // Want a retain here
[tmpObject release];
I have a problem understanding properties.
What kind of property should I write if I want an attribute not be modified by its accessors (return by copy) and be set by reference (retain).
Example :
MyType* theAttribute = MyObject.attribute;
[theAttribute changeSomething]; // Does not have to change the MyObject attribute, working with a copy return
MyType tmpObject = [[MyType alloc] init];
MyObject.attribute = tmpObject; // Want a retain here
[tmpObject release];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在标头中将属性声明为保留:
在实现文件中合成 iVar:
但提供您自己的 getter,它将覆盖合成的 getter:
我知道我不会自动释放返回的对象,但由于问题没有指定 iOS,我是从垃圾收集环境的角度写这篇文章的。
declare the property as retain in the header:
In the implementation file synthesize the iVar:
But provide your own getter which will override the synthesized one:
I know I'm not autoreleasing the returned object, but since the question doesn't specify iOS, I'm writing this from the perspective of a garbage collected environment.
在这种情况下,您应该自己编写 getter 和 setter。
In such case you should write getter and setter by yourself.
您可能会编写自己的访问器,但具体如何取决于您是否希望复制的“get”返回自动释放:
完成“复制”的惯用方法是拥有一个正常的“为访问器保留”属性,并支持
-copy
或-mutableCopy
方法。后两者是语义复制对象的标准,并且返回的对象应该具有保留所有权。如果您想让访问器
-foo
返回“foo”的副本,以便调用者无法操作内部版本,那没问题,但是您需要自己将其写入看起来像这样:-
You'd probably write your own accessor(s), but exactly how depends on whether you want the copied "get" return to be autoreleased or not:
The idiomatic way of accomplishing "copy" this is to have a normal "retain" property for accessors, and support the
-copy
or-mutableCopy
method also. The latter two are the standard for semantically copying an object, and the returned object should have a retain ownership.If you want to have the accessor
-foo
return a copy of "foo" so that the caller can't manipulate the internal version, that's OK, but then you'd write it yourself to look like this:-
我建议不要通过副本返回。这会阻碍你进行内存管理。是自动释放的吗?不保留?问题太多了。
相反,我推荐这个:
或者其他什么。
I would suggest not returning by copy. This will snag you up in memory management. Is it auto-released? Not retain'd? Too many questions.
Instead, I recommend this:
or something.