2010-07-08 26 views
0

這裏是代碼應用轟然插入對象到數組

NSString* favPlistPath = [[NSBundle mainBundle] pathForResource:@"favs" ofType:@"plist"]; 
NSMutableDictionary* favPlistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:favPlistPath]; 

favArray = [[NSMutableArray alloc] initWithCapacity:100]; 
for(int i=0; i<[favPlistDict count]; i++) 
{ 
    //app is crashing here 
    [favArray insertObject:[favPlistDict objectForKey:[NSNumber numberWithInt:i]] atIndex:i]; 
} 

在我favs.plist文件中,有一個條目關鍵:0值:5

+0

我們可以有更多的崩潰細節 - 也可以添加一些NSLog來顯示實際值 - 不是你認爲值 – Mark 2010-07-08 08:40:50

+0

這就是完整的代碼。我總是得到0 [favPlistDict objectForKey:[NSNumber numberWithInt:i],儘管我在favs.plist文件中有不同的值。 – coure2011 2010-07-08 08:53:51

+0

由於未捕獲異常'NSInvalidArgumentException'而終止應用程序,原因:'*** - [NSMutableArray insertObject:atIndex:]:嘗試在0處插入nil對象' – coure2011 2010-07-08 08:55:11

回答

1

-objectForKey:如果密鑰不存在於字典中,則返回nil。然後,當您嘗試將對象添加到數組時,會拋出異常,因爲您無法將Nil添加到Cocoa集合中。

如果您希望佔位符值爲零時,您必須使用[NSNull null]

favArray = [[NSMutableArray alloc] init]; 
// the capacity in initWithCapacity: is just a hint about memory allocation, I never bother. 

for(int i=0; i<[favPlistDict count]; i++) 
{ 
    id value = [favPlistDict objectForKey:[NSNumber numberWithInt:i]]; 
    if (value == nil) 
    { 
     value = [NSNull null]; 
    } 
    [favArray addObject:value]; // adds the object to the end of the array 
} 

上述工作僅適用於favPListDict中的鍵是從0到某個值的連續數字的情況。

0

您沒有正確地從你的字典中得到的值。在這些情況下更好的方法是簡單地枚舉字典中的鍵,而不是循環,並希望每個數字都有一個值。我也有一種感覺,你有NSStrings,而不是NSNumbers,這就是爲什麼你會得到nils。

for (NSString *k in favPlistDict) { 
    [favArray addObject:[favPlistDict objectForKey:k]]; 
} 

在這裏,你要添加的對象,而不是把它使用insertObject:atIndex:但因爲你是從0插入和起來,ADDOBJECT:可能是更好的反正。