开发者

Quick Objective-C Question

Consider this line of code, data is a method parameter:

myVar = [[NSMutableData data] retain];

I'm not entirely sure what's going on here, but I think that it's assigning myVar t开发者_如何学Co the data contained in data, incrementing it's reference count. Could someone confirm or deny this? Thanks!

Source of original code snippet- see listing 1: Apple Dev Article


The [ NSMutableData data ] will return an auto-released object (convenience method).

So it will be automatically released when the auto-release pool of the current run-loop is drained.

You are retaining it to prevent this...

Then you are sure you have a valid pointer to the object. That's correct, simply don't forget to release it when you don't need it anymore...

EDIT

For instance:

[ [ [ [ [ [ NSData data ] retain ] release ] autorelease ] retain ];

Retain count is 2, as auto-releasing an object does not change the retain count... But the object has been placed twice in the current auto-release pool, so it will be released twice on the next drain...


You are initializing your myVar variable with a new instance of NSMutableData using a convenience method, and then retaining it.

It's basically the same as myVar = [[NSMutableData alloc] init]; since you are retaining it anyway.


In the above, "data" is a class method that returns a new object of class NSMutableData. Since "data" is not one of the methods that imply ownership of the object it returns, the object's "retain" method is called to establish ownership. The caller is now responsible for relinquishing its ownership claim when it's finished with the object.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜