2011-06-17 80 views
0

在這段代碼中,我選擇了一個字典,將其修改並保存在另一個數組中。但我不知道爲什麼在代碼的第二行,即插入的位置它崩潰的字典(發送到釋放實例消息)我。如何才能解決這個將對象插入到數組中時崩潰

 NSArray *array=[NSArray arrayWithContentsOfFile:plistPath]; 
     NSLog(@"array before %@",array); 
     NSMutableArray *tempArray=[[NSMutableArray alloc]init]; 
     tempArray=(NSMutableArray*)array; 
     NSMutableDictionary *dictToBeChanged=[[NSMutableDictionary alloc]init]; 
     dictToBeChanged=[tempArray objectAtIndex:indexPath.row]; 
     [dictToBeChanged setObject:[NSNumber numberWithBool:YES] forKey:@"isPaid"]; 
     [tempArray removeObjectAtIndex:indexPath.row]; 
     [tempArray insertObject:dictToBeChanged atIndex:indexPath.row]; 
     NSLog(@"array after %@",tempArray); 

回答

2

當您將array指定爲tempArray時,您不會因爲投射而使其變爲可變。

這是一個NSArray,所以你不能添加/刪除它的對象。

另外,有些不需要的初始化(tempArray和dictToBeChanged),因爲你在初始化之後用別的東西覆蓋這些變量(因此產生泄漏)。

你需要的可能是這樣的:

NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:plistPath]; 
NSMutableDictionary *dictToBeChanged = [[[array objectAtIndex:indexPath.row] mutableCopy] autorelease]; 
[dictToBeChanged setObject:[NSNumber numberWithBool:YES] forKey:@"isPaid"]; 
[array replaceObjectAtIndex:indexPath.row withObject:dictToBeChanged]; 

請注意,此代碼不會做你的plist的內容有任何驗證。

1

您可能希望將對象添加到tempArray作爲temparray如下:

[tempArray addObjectsFromArray:array]; 
1

試試這個

NSMutableArray *temp; 
temp=[temp arrayByAddingObjectsFromArray:(NSArray *)otherArray]; 
1

您正在查看內存管理問題。試試這個:

NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:plistPath];//Temp array is unecessary 
NSMutableDictionary *dictToBeChanged; //No need to allocate a new instance 

沒有直接關係,但:

你的頁頭的兩個[INIT]調用是不必要的,造成泄漏。基本上你正在做的是用分配創建一個新的空白數組,並將其分配給一個變量。然後,您立即將您的變量分配給另一個數組,從而失去對剛剛創建的空白數組/字典的引用,這意味着它無法釋放。如果您稍後在代碼中調用版本,則會造成麻煩。