For example: I have a mutable array of BOOLs(or [NSNumber numberWithBool:TRUE]; ). and then I want to change, for example the first value in this array to FALSE.
[array addObject:[NSNumber numberWithBool:TRUE]];
[array objectAtIndex:0] ???
I know a quite strange way to do this task.
[array replaceObjectAtIndex:0 withObject:[NSNumber numberWithBool:FALSE]];
Yes, this fully satisfies me, but I am looking for another way, that is more simple than th开发者_StackOverflowis. Something like [[array objectAtIndex:0] setBoolValue:FALSE];
for example, imagine, if I had UIButton instead of BOOLs: [[array objectAtIndex:0] setHidden:TRUE];
or this is only dreams?
Thanks in advance!
The best way to do this is
[array replaceObjectAtIndex:0 withObject:[NSNumber numberWithBool:FALSE]];
The reason being that [array objectAtIndex:0]
returns an NSNumber
, unlike if you had an array of UIButton
s which would return a UIButton
object that you could operate on. Since you're getting an NSNumber
in return, you can't do anything to do the NSNumber
directly since it doesn't have the methods you want, so you instead have to operate on the array that holds the NSNumber
.
There is nothing stopping you from sending mutating messages to an object in an array, but NSNumber is simply not mutable. That's why you have to replace the number object with a different one. It's nothing to do with the array or the language — you just can't change an NSNumber.
Something to understand here: Arrays are simple collections of pointers to object. Hence, you can easily to things like
((UIButton*)[array objectAtIndex:0]).hidden=TRUE;
Modifying the object is possible and often done. But exchanging one object for another one, you need to use Replacement techniques as you pointed out.
However, simpler objects are, as said above by @Chuck, simply not mutable (like NSNumber).
Please also note that my code above is horrible in terms of stability. How do you certainly know that it's a UIButton you're pulling out of your magic hat (ie. the array?)
精彩评论