views:

34

answers:

2

I have the following utility method declared, where "players" is a NSMutableArray object and a property of my application's view controller. My problem is that "players" still has 0 objects after this method is called.

-(void)addPlayerNamed:(NSString *)name withLife:(NSNumber *)life{
  NSMutableDictionary *newPlayer = [NSMutableDictionary dictionaryWithCapacity:1];
  [newPlayer setObject:life forKey:name];
  [players addObject:newPlayer];
}
+2  A: 

In all likelihood, players is nil. Any message to nil returns 0 or nil.

Chuck
+2  A: 

Have you set players to anything? You have to call this before using it, maybe in the initialiser.

players=[[NSMutableArray alloc] init];

If players is a property, you probably also want to use

self.players

instead of

players

(Although the latter will still work)

Tom H
If `players` is a property with a `retain` attribute, then it will leak unless you use `autorelease` or use the convenience method `[NSMutableArray array]`.
dreamlax
More descriptively, you need to create an array and store its pointer in the `players` instance variable. Until you do, the variable contains `nil`, the pointer to no object. You don't need to create, say, a view in code if you're loading it from a nib; as long as you hooked up the outlet in IB, loading the nib will set the outlet variable for you. In this case, since you're not loading the array from a nib (that isn't possible), you do need to create it in code. (I mention this because some people miss this and create a redundant object, then unknowningly clobber it with one from a nib.)
Peter Hosey