0

I have written a function that adds a ball to an array yet when I check the count it hasnt increased, please can someone advise.

NSMutableArray *_otherBalls;


-(void)addBall{
    CCSprite *target = [CCSprite spriteWithFile:@"redbouncyball.gif" rect:CGRectMake(0, 0, 27, 40)]; 

    [self addChild:target];

    //add to our array
    [_otherBalls addObject:target];

    NSLog(@"Added ball : %@",[_otherBalls count]);
}

The log comes out as

Added ball : (null)

5
  • 1
    _otherBalls.count ? did you mean [_otherBalls count] ? Commented Jul 17, 2011 at 20:30
  • Ah yes, woops, still get (null) though Commented Jul 17, 2011 at 20:32
  • 2
    Perhaps it works, but it's still wrong. count is not declared as a property and you shouldn't use it as such. Commented Jul 17, 2011 at 20:39
  • 1
    Don't use single leading underscores on your variable names. That's an Apple internal coding convention, and they do it so that their names won't collide with yours. Commented Jul 17, 2011 at 21:08
  • Oh really? I was doing that from tutorials that I read! Ill bear that in mind next time, thanks Commented Jul 17, 2011 at 21:32

4 Answers 4

5

From your code it seams that you have never initialized the array. So it' cant store anything. Unless you did in init, but thats hard to guess.

Sign up to request clarification or add additional context in comments.

Comments

4

Try

 NSLog(@"Added ball : %lu",[_otherBalls count]);

count is an integer, not an NSObject.

2 Comments

Actually, it should be %lu.
This is correct, but not the problem... as 0 is semantically the same as nil here.
1

Is _otherBalls an NSMutableArray? Did you make sure to alloc and init _otherBalls?

EDITED: to reflect edited question

3 Comments

Yes it is, I updated the code (and the Q) with the correct count syntax and still get the issue
Ahh spot on, silly mistake. Why didnt XCode crash or throw an exception when I tried to add an item to an uninitialized array?
it is legal (won't cause an exception) to send a message to nil. Quite different from most other languages
0
NSLog(@"Added ball: %d", [_otherBalls count]); 

Try this because you are counting objects in an array and the result would be integer.
If the problem persists then it means that you havent initialized your array

_otherBalls = [[NSMutableArray alloc] init];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.