On Jun 27, 2009, at 7:24 AM, M.S. Hrishikesh wrote:

To create an NSUrl from a file which would be the preferred way

NSString *myFile = @"myFile.xml";

Method A:
NSUrl *myUrl = [NSUrl fileURLWithPath:myFile]

Method B:
NSUrl *myURL = [[NSUrl alloc] initFileURLWithPath:myFile];

Using method B I would need to release my object at some point (this is for iPhone so no GC). Using Method A means no need to release.

This question really has nothing to do with NSURL. It's just a general question about memory management techniques.

Both methods are correct.

Method B (and the attendant necessary release) expresses explicitly the duration of your interest in the object remaining alive. Because of that, there's no slack or ambiguity about the desired lifetime, so it's more likely the object will be deallocated as soon as possible. My understanding is that, on the iPhone with its tighter memory constraints, method B is preferred for that reason.

But with MethodA the object is probably gone as soon as I exit the method correct?

Not quite.  You need to read up on Cocoa's memory management.

Method A uses a convenience constructor. Often, but not always, convenience constructors return autoreleased objects, which will live _at least_ as long as the current autorelease context. If you're explicitly managing autorelease pools, then you should already know when that will be. Otherwise, it basically means "until flow of execution flows out of your code and back to the framework which called your code". So, it's not as soon as the method exits, because 1) the method may have been called by another method of yours, in which case execution hasn't returned to the framework, and 2) your "as soon as" implies a maximum lifetime, whereas my "at least" is intended to make clear that the lifetime guarantee provides a minimum lifetime.

This difference between a maximum guarantee vs. a minimum guarantee is why method B would be preferred on the iPhone. Method A may result in an object living longer than strictly necessary for your app to function, and so increases memory pressure.

Even for convenience constructors which don't return autoreleased objects, the contract is basically the same. Unless otherwise documented, the object is guaranteed to live at least as long as the current autorelease context.

(And, of course, if you receive an object from a convenience constructor but need to make sure it lives beyond that, you need to retain it while you need it and then later balance your retain with a release.)

Regards,
Ken

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to