Still have some difficulties to understand Obj-C's gestion of memory and some of its concepts.
So my main class contains a NSMutableArray
containing some characters and their list of weapons. It's like this :
In Main class.h
@property (nonatomic, retain) NSMutableArray *players;
In Main class.m's init
for(int i = 0 ; i < 30 ; i++)
{
[players addObject:[[PlayerInGame alloc] init:[self.tabPlayers objectAtIndex:i] :[self.tabWeapons:objectAtIndex:i]]];
}
PlayerInGame.h
@property (nonatomic, retain) NSMutableArray *weaponsList;
PlayerInGame.m
- (id) init : (Player*) player : (Weapon*) weapon
{
[self.weaponsList addObject:weapon];
// Then I try NSLog of weaponsList's count.
}
Here weaponsList is always empty. What is wrong?
You have to alloc your array before add any object in it. you can use following code in
viewDidLoad
methodI've not seen weaponList object allocation. Do you initialize it?
PS: Minor advice. Method "- (id) init : (Player*) player : (Weapon*) weapon" signature will look better and being used easier if you change it as
The other answers are right. On any other language if you reference a unallocated object you will get a NullPointerException. But in objective C the method sent to nil just returns 0 and it won't crash the app.. If you want further read, read this
That is why
didn't crash, while in java if you try to add object to a unallocated array your program will crash.. As other answers pointed out, the statement
alloc memory to store array, and a reference is given back to to variable weaponList. Now weaponList != nil.
I aslo suggest to change a bit your init syntax and init the array with object: