enumerating NSArray, Whats the problem ??

What’s wrong with the below code ?

[callMethods readFromFile:fileId forCallback:^(BOOL success, id result) {
if (result) {
NSArray *files = result;
int cntr = 0;
// will crash here
for (id obj in files) {
cntr++;
}
}
callback(YES, [NSString stringWithFormat:@"%d", cntr]);
}

The reason it will crash, is because the enumeration doesn’t check the class type. If we get invalid data from the method, other than an array and pass it to this it will crash.

The easiest way to fix this is as shown below :

[callMethods readFromFile:fileId forCallback:^(BOOL success, id result) {
if (result != NULL) {
NSArray *files = result;
int cntr = 0;
// check if its really an array
if([files isKindOfClass:[NSArray class]]){
// will crash here
for (id obj in files) {
cntr++;
}
}
}
callback(YES, [NSString stringWithFormat:@"%d", cntr]);
}

In

Leave a Reply

Your email address will not be published. Required fields are marked *