codereviewanskquestions
codereviewanskquestions

Reputation: 13998

Objective C, A Question about releasing an object

If I do something like

address = [[NSString alloc] initWithData:addressData encoding:NSASCIIStringEncoding];

Then I know that I need to do like [address release] after I am done with using it. Because "alloc" increases the reference count of "address" variable so that I need to do

 [address release]

But I am not sure that I need to release if I do something like

 NSData *addressData = [NSData dataWithBytes:buf length:address_len];

I don't see any "alloc" in this statement..So do I still need to do [addressData release] after I am done with this?

Thanks in advance...

Upvotes: 0

Views: 62

Answers (4)

Mahesh
Mahesh

Reputation: 34655

No, there is no need to release in your second statement. If you alloc, copy, new, then you should release the objects.

Objective C Memory Management for Lazy People has very useful info as to when to release objects.

Upvotes: 0

xyzzycoder
xyzzycoder

Reputation: 1831

You do not need to do the release in your second example. The general rule is that you are responsible for a release if you call alloc, retain, or copy.

Upvotes: 0

DarkDust
DarkDust

Reputation: 92414

No, you don't. You only need to release (or autorelease) an object if the method you got the object from is alloc, contains the word copy, or if you've retained the object.

Upvotes: 1

Abizern
Abizern

Reputation: 150745

Nope. In this case you can safely assume that the memory is autoreleased.

All explained in the Memory Management Ownership Policy

Upvotes: 1

Related Questions