问题
I'm trying to add sprites to a NSMutableArray
but it's not adding them. This is what I have:
NSMutableArray *tail;
CCSprite *block;
int j;
-(void)handleTail:(CCSprite*)pos{
CGPoint point= pos.position;
block = [CCSprite spriteWithFile:@"Icon-Small-50.png"];
//Adding the tail blocks
block.scale = .8;
block.color = ccGREEN;
block.position = point;
NSLog(@"Block Pos (%f,%f)",block.position.x,block.position.y);
//CGPoint playerPos = piece.position;
originalPos = point;
if ([tail count] < maxLength) {
[tileMap addChild:block];
[tail addObject:block];
NSLog(@"Tail length:%i",tail.count);
j+=1;
}
if (j == 3) {
NSLog(@"J called");
[tail removeObjectAtIndex:0];
}
}
I don't understand why this isn't working?
回答1:
You have not alloc+inited the tail
.
In awakeFromNib or init or viewDidLoad ( which ever is applicable for your class) use
tail=[[NSMutableArray alloc] init];
Suggestion NOTE : Try to follow naming convention.
As tail
is an array (plural) you should use tails
.
回答2:
You forget to alloc init NSMuttableArray
tail = [[NSMuttableArray alloc]init];
without alloc and init your array you cannot add object to it
when you try to access its member it returns nil
try NSLog (@"%@",tail); it returns
回答3:
You need to instantiate your NSMutableArray.
tail = [NSMutableArray array];
回答4:
You need to allocate and initialize the array.
Something like:
tail = [NSMutableArray array];
来源:https://stackoverflow.com/questions/14940873/nsmutablearray-not-working-at-all