问题
I'm creating bugs over and over by failing to notice the consequences of [NSArray count] being unsigned
. Today's example is relatively unusual:
for (int i = -1; i < [myArray count]; i++) {
This loop never executes! You need (int)[myArray count]
. My usual mistake is:
for (int i = 0; i < [myArray count] - 1; i++) {
If the array is empty, this loop executes basically forever because [myArray count]-1
overflows the unsigned int
.
I do use fast enumeration where possible, but in this project I very often need to refer the objects at indexes i-1
and i+1
while processing object i
and it doesn't seem to lend itself to that. Any other tips for avoiding these bugs, other than just being less incompetent?
回答1:
Firstly, there's a warning you can turn on to pick up these issues. I think it's "sign comparison", the command line flag is -Wsign-compare
.
If you want to iterate over the elements of an array but you need the index, the neatest way (in my opinion) is -enumerateObjectsUsingBlock:
[myArray enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop)
{
NSlog(@"Object at index %lu is %@", (unsigned long) idx, obj);
if (idx > 0)
{
NSlog(@"Previous object is %@", [myArray objectAtIndex: idx - 1]);
}
if (idx + 1 < [myArray count])
{
NSlog(@"Next object is %@", [myArray objectAtIndex: idx + 1]);
}
}];
回答2:
You can still using the index while doing fast enumeration, just do:
for (id object in myArray)
{
NSInteger anIndex=[myArray indexOfObject:object];
}
回答3:
As per my suggestion, You can go with Antonio MG answer
And you want loop then try the below code
int totalObj = myArray.count-1;
for (int i = 0; i<totalObj; i++) {
// Write your code
}
回答4:
JeremyP's answer is the best. If for some reason you don't want to use fast enumeration to run though the for loop, one suggestion is to just learn to use unsigned integers for your indices.
for (NSUInteger i = 0; i < something.count; i++) {
...
}
来源:https://stackoverflow.com/questions/21479201/constant-bugs-from-nsarray-count-being-unsigned