开发者

Objective C: retain vs alloc - revisited

开发者 https://www.devze.com 2023-02-01 04:09 出处:网络
I\'m wondering about allocating an object which has a retain property, something like that: RootViewController *viewController;

I'm wondering about allocating an object which has a retain property, something like that:

RootViewController *viewController;

@property (nonatomic, retain) RootViewController *viewController;


@implementation ...

viewController = [[RootViewController alloc] init];

since it's not right to do something like that:

self.viewController = [[RootViewController alloc] init];

as this will raise the object retain count by开发者_StackOverflow中文版 2 and you will have to release your object twice, one of whom is in the dealloc method.

So would it be better to use an assign property if I'm allocating my object? or when would it be necessary to retain an object that I'm allocation using the alloc method.

I'm very confused about this issue so can you please exemplify to me how this situation is valid.

Thanks a lot in advance and I'd really appreciate it.

Regards,


When you're passing an object to somewhere else that you expect to take control of it, it's standard practice to autorelease it:

self.viewController = [[[RootViewController alloc] init] autorelease];

Or you can just release it yourself after setting the variable:

RootViewController *controller=[[RootViewController alloc] init];
self.viewController = controller;
[controller release];

Your first example isn't necessarily bad practice, although there are certainly programmers who believe it is. It depends a lot on the context.

Using assign would likely be wrong in this circumstance.


Assign would be wrong. The 'retain' attribute means that your object takes ownership of the viewController. It's OK to assign it like that in your initializer, but the 'retain' attribute determines what happens after the object is created if you set viewController to a different object.

For a retained attribute, the generated setter will look something like this:

- (void)setViewController: (UIViewController*)value
{
    if (viewController != value) {
        [viewController release];
    }
    viewController = [value retain];
}


If you setup the property as retain, then using autorelease would be appropriate as follows:

self.viewController = [[[RootViewController alloc] init] autorelease];

Make sure you use "self." above to make sure your using the synthesized setter, which will take care of the details around the retain.


No, what you should do is autorelease your RootViewController, or assign to the ivar directly in the case of above, where you take ownership of the object from the outset.

0

精彩评论

暂无评论...
验证码 换一张
取 消