padam thapa
padam thapa

Reputation: 1477

NSArray initWithObjects: Memory Leak

Here is my code:

    - (void)viewDidLoad{
[super viewDidLoad];

self.authorList = [[NSArray alloc] 
                   initWithObjects:@"Christie, Agatha", 
                   @"Archer, Jeffrey", nil];

self.title = @"Authors";

}

I am getting memory leak at line where i am allocating and init the array authorlist. I tried to put autorelease on authorlist but it says that "Object sent- autorelease sent too many times". I am still learning memory management.

Gracias.

Upvotes: 0

Views: 326

Answers (4)

Ravi Kumar Karunanithi
Ravi Kumar Karunanithi

Reputation: 2218

Use this

 self.authorList = [[[NSArray alloc] 
               initWithObjects:@"Christie, Agatha", 
               @"Archer, Jeffrey", nil] autorelease];

Upvotes: 0

Bharathi
Bharathi

Reputation: 485

You should not allocate the property object directly.

You should allocate like this :

 - (void)viewDidLoad{
      [super viewDidLoad];

       NSArray *tempArray = [[NSArray alloc] 
               initWithObjects:@"Christie, Agatha", 
               @"Archer, Jeffrey", nil];
       self.authorList = tempArray;
       [tempArray release];


      NSString *titleString = @"Authors";
      self.title = titleString;
      [titleString release];
 }

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122391

The setter method for authorList will retain the array so you need to release it immediately after calling it:

NSArray *list = [[NSArray alloc] 
                initWithObjects:@"Christie, Agatha", 
                @"Archer, Jeffrey", nil];
self.authorList = list;
[list release];

Or you can autorelease it:

self.authorList = [[[NSArray alloc] 
                   initWithObjects:@"Christie, Agatha", 
                   @"Archer, Jeffrey", nil] autorelease];

Upvotes: 5

Volodymyr B.
Volodymyr B.

Reputation: 3441

Did you wrote dealloc method in your Class?

If you did not use ARC http://cocoa-touch.blogspot.ie/2008/09/memory-management-on-iphone.html

Upvotes: 0

Related Questions