Reputation: 8158
I've got an array of NSNumber objects created thusly:
myArray = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithDouble:0.0],
[NSNumber numberWithDouble:0.0],
[NSNumber numberWithDouble:0.0],
[NSNumber numberWithDouble:0.0],
[NSNumber numberWithDouble:0.0], nil];
(Though just occurred to me that I could have done
myArray = [NSMutableArray arrayWithObjects: object1, etc..., nil];
and skipped the alloc entirely. Which would be better?)
Anyway, it's tangential to my question:
Over the life of the app, the values get changed. At a certain point, I want to reset them all to zero. Here's how I'm doing it now:
for (NSNumber *number in myArray) {
number = [NSNumber numberWithDouble:0.0];
}
But the Static Analyzer throws a warning because it thinks 'number' is an unused variable (which it technically is - set and then never used again). Is there a better way to zero out all the elements of the array? Perhaps replace the array with a new one? What would be fastest and avoid the static analysis warning?
Upvotes: 3
Views: 1994
Reputation: 95355
With regards to creating an array, remember that alloc
+initWithObjects:
requires an explicit release afterwards, whereas the arrayWithObjects:
convenience method does not (and also, it will not survive an iteration of the run loop unless you retain it).
for (NSNumber *number in myArray) {
number = [NSNumber numberWithDouble:0.0];
}
This loop doesn't do what you think it does. number
simply points to an NSNumber
instance, and all you're doing is changing number
to point to another instance of NSNumber
, it does not modify the original instance of NSNumber
in myArray
.
NSNumber
instances are immutable, so the only way to set them all to zero would be to completely erase the contents of myArray
and fill it back up with [NSNumber numberWithDouble:0.0]
NSUInteger count = [myArray count];
[myArray removeAllObjects];
while(count--)
[myArray addObject:[NSNumber numberWithDouble:0.0]];
Upvotes: 8