简体   繁体   English

在objective-c中保留对象

[英]retain object in objective-c

I'm doing a set method: 我正在做一个设置方法:

OBS: somobject is an attribute of a class. OBS:somobject是类的属性。

– (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. 在[somobject autorelease]上,我声明我不想在setSomeObject范围内拥有该对象。

Does the "someobject" retained by another object will be released? 是否会释放另一个对象保留的“ someobject”? Or the object will be released just on setSomeObject method? 还是仅在setSomeObject方法上释放对象?

If the someobject class atribute already exists? 如果someobject类属性已经存在?

What will be the behavior of this object? 该对象的行为是什么?

I'd rename the parameter in the method so that it's different from the ivar: 我在方法中重命名了参数,使其与ivar不同:

– (void)setSomeObject:(SomeObject *)newObject 
{
    [someobject autorelease];

    someobject = [newObject retain];
}

Also you should read Apple docs for memory management and @property and @synthesize . 另外,您应该阅读Apple文档以了解内存管理以及@property@synthesize

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. 有关您的内存管理问题,请查阅Apple的编程指南。

What you need to accomplish in a setter is: 您需要在二传手中完成的工作是:

  1. Release any old object 释放任何旧物体
  2. Retain the new object 保留新对象
  3. Assign the new object to your instance variable 将新对象分配给您的实例变量

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: 将方法参数和实例变量命名为(IMHO)一样令人困惑,并且会向您发出编译器警告,但是如果您绝对坚持这样做,则可以使用“ self->”来指定您所指的是实例变量:

– (void)setSomeObject:(SomeObject *)someobject {

[self->someobject autorelease];

self->someobject = [someobject retain];

return;

} }

Finally, unless your setter method has to do something special, you should consider using @synthesize to have your setter/getter automatically generated. 最后,除非您的setter方法必须执行特殊操作,否则应考虑使用@synthesize自动生成您的setter / getter。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM