NSArray construction causing app crash
My app crashed, is this correctly constructed?
NSArray *array = [mapView.annotations filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(self isKindOfClass: %@)", [MapLocation class]]];
if (array != nil)
{
annotation = [array objectAtIndex:0];
}
I see that array isn't nil but it has 0 objects (on debug). Is correctly 开发者_C百科constructed?
NSArray will raise an exception if you access something out of its bound. If the array is empty, accessing element at index 0 is out of its bound.
You can check if the array contains elements by calling [array count]
eg:
NSArray *array = [mapView.annotations filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(self isKindOfClass: %@)", [MapLocation class]]];
if([array count] > 0) // No need to check if the array is != NULL, the runtime won't send messages to NULL
{
annotation = [array objectAtIndex:0];
}
精彩评论