在 Objective-C 中保留对象
我正在做一个set方法:
OBS:somobject是一个类的属性。
– (void)setSomeObject:(SomeObject *)newSomeobject { [someobject autorelease]; someobject = [newSomeobject retain]; return; }
在 [somobject autorelease] 上,我声明我不希望更多人拥有 setSomeObject 范围内的对象。
另一个对象保留的“someobject”是否会被释放?或者仅在 setSomeObject 方法上释放对象?
如果 someobject 类属性已经存在?
这个对象将会有什么行为?
I'm doing a set method:
OBS: somobject is an attribute of a class.
– (void)setSomeObject:(SomeObject *)newSomeobject { [someobject autorelease]; someobject = [newSomeobject retain]; return; }
on [somobject autorelease] I declare that I don't want more to own the object under the scope of setSomeObject.
Does the "someobject" retained by another object will be released? Or the object will be released just on setSomeObject method?
If the someobject class atribute already exists?
What will be the behavior of this object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会重命名方法中的参数,使其与 ivar 不同:
此外,您还应该阅读 Apple 文档以了解内存管理以及
@property
和@synthesize
。I'd rename the parameter in the method so that it's different from the ivar:
Also you should read Apple docs for memory management and
@property
and@synthesize
.您有一个严重的问题,因为您似乎有两个同名的变量(方法参数和实例变量)。编译器(以及这个问题的读者,就此而言)无法辨别您所指的内容。
对于内存管理问题,请查看 Apple 的编程指南。
You have a significant problem, in that it seems you have two variables (the method parameter and an instance variable) with the same name. The compiler (and readers of this question, for that matter) can't tell to which you're referring.
For your memory management problems, check out Apple's programming guide.
您需要在 setter 中完成的是:
当然,如果您按字面顺序执行此操作,则在旧对象被释放的情况下,您可能会过早释放该对象。 &新对象是相同的。这就是“自动释放”派上用场的地方,因为它安排要释放的对象,但只有在方法返回之后。
命名方法参数&实例变量相同(恕我直言)令人困惑,并且会给你一个编译器警告,但如果你绝对坚持这样做,你可以使用“self->”指定您引用的是实例变量:
}
最后,除非您的 setter 方法必须做一些特殊的事情,否则您应该考虑使用 @synthesize 自动生成您的 setter/getter。
What you need to accomplish in a setter is:
Of course, if you do it literally in that order, you risk releasing the object too soon in the case where old & new objects are the same. That's where the "autorelease" comes in handy, because it schedules the object to be released, but only after your method returns.
Naming the method parameter & instance variable the same is (IMHO) confusing, and will give you a compiler warning, but if you absolutely insist on doing it that way, you can use "self->" to specify that you're referring to the instance variable:
}
Finally, unless your setter method has to do something special, you should consider using @synthesize to have your setter/getter automatically generated.