views:

59

answers:

1

I can't say I really understand the memory handling in Objective-C so I have a couple of questions concerning that.

  • Do I have to remove the objects "url" and "urlRequest" in the box below or does "urlConnection" take on the responsibility for doing that?

    NSURL* url = [NSURL URLWithString:url];
    NSURLRequest* urlRequest = [[NSURLRequest alloc] initWithURL:url];
    NSURLConnection* urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
    
  • What is the difference between the following object creations. Is the ref. counter retained in all cases?

    [[NSString alloc] init];  
    [[NSString alloc] initWithFormat:...];  
    [NSString stringWithString:...];  
    
  • When assigning a property, is the ref. count always retained regardless of whether "assign" or "retain" was set as attribute?

+1  A: 

Generally speaking if you obtain an object through a method begining alloc, new or copy, you become responsible for releasing that object. Hence in your first query you'll need to release urlRequest and urlConnection. The url object is an example of an object which you don't need to release, as it is instantiated using a static factory method (URLWithString).

[[NSString alloc] init];

Will initialise a NSString with a reatin count of 1.

[[NSString alloc] initWithFormat:...];  

Again, results in a NSString with retain count of 1. The only difference is you've called a different initializer.

[NSString stringWithString:...];

Creates an autoreleased NSString that is guranteed to remain valid during the current event loop.

As for property attributes, assign will not retain the object passed to the setter.

I know it's a bit dry but the Memory Management Guidelines are a really good reference for this type of question.

mmccomb
Is it OK to use autorelease, as you mentioned, on iPhone?
AOO
Absolutely! The concept of autoreleasing objects is a major part of the memory management platform on the iPhone OS.
mmccomb
I've found describing things in terms of retain count just confuses people; ownership is a much simpler principle. Otherwise, good answer.
rpetrich
As you get up to speed, to help you find mistakes in releasing objects, use Build and Analyze in Xcode. That's shift-command-A. It won't do your learning for you but it will help you get a 'feel' for memory management.
willc2