Iphone NSARARY构造导致应用程序崩溃
我的应用程序崩溃了,这个构造正确吗Iphone NSARARY构造导致应用程序崩溃,iphone,objective-c,nsarray,Iphone,Objective C,Nsarray,我的应用程序崩溃了,这个构造正确吗 NSArray *array = [mapView.annotations filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(self isKindOfClass: %@)", [MapLocation class]]]; if (array != nil) { annotation = [array objectAtIndex:0]; } 我看到数组不是nil,但它有0
NSArray *array = [mapView.annotations filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(self isKindOfClass: %@)", [MapLocation class]]];
if (array != nil)
{
annotation = [array objectAtIndex:0];
}
我看到数组不是nil,但它有0个对象(在调试时)。是否正确构造?如果访问超出其边界的内容,NSArray将引发异常。如果数组为空,则访问索引0处的元素超出其界限。
NSArray *array = [mapView.annotations filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(self isKindOfClass: %@)", [MapLocation class]]];
if (array != nil)
{
annotation = [array objectAtIndex: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];
}
六羟甲基三聚氰胺六甲醚。。。。然后使用[array count]>0条件。