0

My array:

NSMutableArray *squareLocations;

CGPoint dotOne = CGPointMake(1, 1);
[squareLocations addObject:[NSValue valueWithCGPoint:dotOne]];

CGPoint dotTwo = CGPointMake(10, 10);
[squareLocations addObject:[NSValue valueWithCGPoint:dotTwo]];

CGPoint dotThree = CGPointMake(100, 100);
[squareLocations addObject:[NSValue valueWithCGPoint:dotThree]];

int num = [squareLocations count];

for (int i = 0; i < num; i++)
{
    NSValue *pointLocation = [squareLocations objectAtIndex:i];
    NSLog(@"%@", pointLocation);
}

When I ask squareLoctions for an object count, it returns zero? But just above asking for count I added three NSValue objects??? Anyone have any ideas?

Till
  • 27,559
  • 13
  • 88
  • 122
Not My Name Car
  • 59
  • 1
  • 1
  • 8

2 Answers2

7

You need to initialise the array first

NSMutableArray *squareLocations = [[NSMutableArray alloc] init];
Rog
  • 18,602
  • 6
  • 76
  • 97
  • 1
    +1 for correct answer. I just thought I should add an answer that is a little more verbose to help that fella. – Till Mar 14 '13 at 02:06
  • 1
    Super selective +1 because I prefer brief answers. The asker should then research why that is the case if they don't understand. – borrrden Mar 14 '13 at 02:37
  • @borrrden big smile for your comment :D ... you certainly are right. I just felt like I should waste a minute. – Till Mar 14 '13 at 02:44
  • @Till My comment doesn't reflect on your answer at all, only on my preferences ^^. – borrrden Mar 14 '13 at 02:46
  • @borrrden totally got that - I just liked to read it. – Till Mar 14 '13 at 02:49
  • Hahaha I can't believe I didn't notice that. Sorry for the dumb question guys haha. Thanks for the answers!!! – Not My Name Car Mar 14 '13 at 15:41
3

That array is returning 0 because you are actually not asking an array for its size.

The object you assume to be an array has neither been allocated, nor being correctly initialised.

You are asking an instance that is currently initialised as being nil. The fun part is that it does not crash as Objective-C will allow you to call any method (selector) on a nil instance (well, that term is not quiet correct). Just, those nil instances will always return 0, NO, 0.0f, 0.0 or nil depending on the expected type when being asked for their return values. In other words, it always returns a value that when being casted towards the expected type, will be set to zero.


To fix that issue you will need to allocate, initialise and assign an instance of an NSMutableArray to your variable.

That could either been done using the proper alloc and init method combination:

NSMutableArray *squareLocations = [[NSMutableArray alloc] init];

Or you could use one of the convenience constructors like for example:

NSMutableArray *squareLocations = [NSMutableArray array];

Next time you encounter such weird behaviour, check if the instance in question is not nil first.

Till
  • 27,559
  • 13
  • 88
  • 122