ArisRS
ArisRS

Reputation: 1394

NSMutableArray with custom objects?

I have a custom class:

 @interface Player : NSObject {
   NSInteger mPlayerNo;
 }

 -(id) initWithNum:(NSInteger) playerNum;

 @implementation Player

 -(id) initWithNum:(NSInteger) playerNum
 {
   if(![super init])
   return nil; 
   ... 
   mPlayerNo=playerNum;
   return self;
 }

 @end

I need the array of the Player objects in the other programm class:

 @interface Spec : NSObject  {
    NSMutableArray * mPlayers;
    ...
  }

So, I am trying to fill mPlayers arr in the init method of the Spec class like this:

- (id)init {
   if(![super init])
      return nil; 
   NSMutableArray * _array=[[NSMutableArray alloc] init];
   mPlayers=_array;
   [_array release];
   Player * _player=[[[Player alloc] initWithNum:(NSInteger)1]autorelease];
   [mPlayers addObject:_player]; // crashes with EXC_BAD_ACCESS

It doesn't work. But if I change

   NSMutableArray * _array=[[NSMutableArray alloc] init];
   mPlayers=_array;
   [_array release];

with

   mPlayers=[[NSMutableArray array]retain];

All works fine. It is something strange for me. Please, help to understand the problem with alloc init.

Upvotes: 1

Views: 1849

Answers (3)

Robert
Robert

Reputation: 63

If you assign the Array you created to mPlayers, this does not affect the retain count. If you then call release, the retain count reaches zero and the object gets deallocated.

As a deeper understanding of this behaviour is essential for Objective-C development, you might want to have a look at the documentation Apple provides

Upvotes: 2

andyvn22
andyvn22

Reputation: 14824

The problem is that you're releasing your array before using it.

NSMutableArray * _array=[[NSMutableArray alloc] init]; //Retain count of 1

mPlayers=_array; //Still 1.
//Adding a new pointer to the same object doesn't affect the object's retain count.

[_array release]; //Now it's 0. Array is gone!

Upvotes: 4

bbum
bbum

Reputation: 162712

   NSMutableArray * _array=[[NSMutableArray alloc] init];
   mPlayers=_array;
   [_array release];

Here you are creating an array, then immediately releasing it. The +alloc implies a retain and you are balancing it by that release.

The assignment is irrelevant.

Upvotes: 2

Related Questions