2011-02-11 74 views
0

我的應用程序崩潰了,這是正確構造?NSArray構建導致應用程序崩潰

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

我看到該數組不是零,但它有0個對象(在調試時)。正確構造?

+4

嗯....然後用[陣列計數> 0的條件。 – Mahesh 2011-02-11 14:12:31

回答

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]; 
}