Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone NSARARY构造导致应用程序崩溃_Iphone_Objective C_Nsarray - Fatal编程技术网

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条件。