开发者

Memory allocation in Objective C

开发者 https://www.devze.com 2023-01-13 15:04 出处:网络
I have a simple question. I was referring \"Your first iOS application\" document by apple.I found that the class has a property called myViewController:

I have a simple question. I was referring "Your first iOS application" document by apple.I found that the class has a property called myViewController:

@interface applicationClass
{
   MyViewController *myViewController
}

Now to assign a memory to this pointer, the code shown 开发者_开发百科is:

MyViewController *aViewController = [[MyViewController alloc]
            initWithNibName:@"MyViewController" bundle:[NSBundle mainBundle]];
[self setMyViewController:aViewController];
[aViewController release];

My doubt here is, what is wrong if this is done as follows:

self.myViewController = [[MyViewController alloc]
            initWithNibName:@"MyViewController" bundle:[NSBundle mainBundle]];

I cannot find this kind of instantiation where a property is assigned directly in many of the documents. Instead, a temporary memory is allocated and then it is retained by the property. Can anyone guide me if I am wrong ?


If you call methods which have alloc or copy in their names you get objects with a retain count of +1 and thus you are responsible for releasing it after use.

Now, if you assign to a property that is defined as @property(retain,...) ... then the @synthesize'd method takes care that retain and release are called correctly. So if you do self.foo = bar then the retain count of bar is increased by one.

Here, you got an object with retain count 1 from your alloc/init. Then you assign it to your property, and the retain count climbs to 2, which is too high (you only have one reference to it, not two). Two solutions: either the first code block you've cited, it stores the object in a variable and can then call release to immediately "fix" the retain count to 1 again. Or, you can do this:

self.myViewController = [[[MyViewController alloc] initWithNibName:@"MyViewController" bundle:[NSBundle mainBundle]] autorelease];

The autorelease will make sure that at a later time release is being called on the object thus again "fixing" the retain count. You cannot replace autorelease withrelease` here as the retain count would drop to 0 before it gets assigned to the property, thus it would get deallocated before it gets passed to the property.


With this you are retaining your object twice: in self. (if you have set retain in your property of couse) and in [MyViewController alloc]. You only want to retain the object once ....

0

精彩评论

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