NSArray构造导致应用程序崩溃

时间:2011-02-11 14:09:57

标签: iphone objective-c nsarray

我的应用程序崩溃了,这是否正确构建?

NSArray *array = [mapView.annotations  filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(self isKindOfClass: %@)", [MapLocation class]]];
if (array != nil)
{
    annotation = [array objectAtIndex:0];
}

我看到数组不是nil但它有0个对象(在调试时)。是否构造正确?

1 个答案:

答案 0 :(得分:2)

如果您访问超出其范围的内容,NSArray将引发异常。如果数组为空,则访问索引0处的元素超出其范围。 您可以通过调用[array count]来检查数组是否包含元素,例如:

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];
}
相关问题