Add to NSMutableArray
I have 2 doubles with each iteration I want add to a NSMutableArray
but I can't seem to make it happen.
NSMutableArray *touchArray = [[NSMutableArray alloc]init];
[touchArray addObject:[NSString stringWithFormat:@"%d", "%d", tapTotal, touchBegin]];
NSLog(@"array: %@", touchArray);
The console prints 14108 as the value for the array, I'm not sure where that's coming from, it's not the v开发者_如何学编程alue of either on of the variables. And XCode complains on the first two lines, "local declaration of 'touchArray' hides instance variable. I know I'm doing at least one thing wronl
Thanks for any help, Robert
first, the 'local declaration problem':
You have already declared touchArray elsewhere, therefore you don't need to redeclare, just (possibly) initialize like so touchArray = [[NSMutableArray alloc] init];
Secondly: the double problem: theres quite a few: you are adding a string to the array, not two doubles. to add a double, you need to wrap it in an NSNumber first:
[touchArray addObject:[NSNumber numberWithDouble:firstDouble]];
[touchArray addObject:[NSNumber numberWithDouble:secondDouble]];
also you want to print out each variable in the array to check it I would believe, not the array object itself. for this: NSLog(@"array[0] = %g", [[touchArray objectAtIndex:0] doubleValue]
edit for answer clarification: my answer assumes the poster wants to add two doubles seperately to the array, not a string with two values in it. Thought i might clear that up as kenny and I had different outtakes :)
there is a lot wrong here, so I would suggest maybe trying to read an objective c/iphone development book to learn more.
You are using +stringWithFormat:
wrongly. Only the first string can be the format string. The rest will be passed as parameter to format. In your code, the format string is "%d"
, so the runtime will expect exactly 1 integer. It sees the address to the 2nd "%d"
is 14108, so it will print this as an integer.
The correct code should be:
[NSString stringWithFormat:@"%g %g", tapTotal, touchBegin]
(Usually, %d
→ int
, %u
→ unsigned
, %g
→ double
and CGFloat
, %@
→ Objective-C objects, etc.)
"local declaration of 'touchArray' hides instance variable"
shows you already have defined same array anywhere else in the code locally. Or you defined it into your .h file
NSLog
cant directly print what you have inside a array. If you added a string as its first object (i.e. index 0) then you should print like this-
NSLog(@"array: %@", [touchArray objectAtIndex:0]);
Cheers
精彩评论