2011-06-24 54 views
0

我在將對象添加到iPhone SDK中的NSArray時遇到問題。問題是它只添加我的NSDictionary的最後一個對象。這是代碼:將對象添加到iPhone SDK中的數組時出現問題

NSArray * processes = [[UIDevice currentDevice] runningProcesses]; 
for (NSDictionary * dict in processes){ 
    runningprocesses = [[NSMutableArray alloc] init]; 
    NSString *process = [dict objectForKey:@"ProcessName"]; 
    [runningprocesses addObject:process]; 
} 

當我的NSLog [dict objectForKey:@"ProcessName"]它顯示我所有的進程,但如果我嘗試添加他們只增加了最後一個。會發生什麼?

+0

因爲在你的代碼中,每次循環迭代時,runningprocesses數組都指向一個新的實例。 – Mohit

回答

2

我重新編輯你的代碼,我建議你嘗試,而不是:

NSArray * processes = [[UIDevice currentDevice] runningProcesses]; 
NSMutableArray *runningprocesses = [[NSMutableArray alloc] initWithCapacity:[processes count]]; 
for (NSDictionary * dict in processes){ 
    NSString *process = [dict objectForKey:@"ProcessName"]; 
    [runningprocesses addObject:process]; 
} 

這個工作對我來說,當我嘗試:]

+0

+1:使用initWithCapacity的唯一答案:用於創建NSArray – redent84

+0

是的,我是一個「容納納粹」......它是我真正相信可變數據的唯一方法。 –

0

在代碼中,每次循環迭代中,runningprocesses陣列正在指向一個新的實例。

要修復它移到您的陣列實例外的for循環:

NSArray * processes = [[UIDevice currentDevice] runningProcesses]; 
NSMutableArray *runningprocesses = [[NSMutableArray alloc] init]; 
for (NSDictionary * dict in processes){ 

    NSString *process = [dict objectForKey:@"ProcessName"]; 
    [runningprocesses addObject:process]; 
} 
0

您正在嘗試每次分配「runningprocesses」數組中的for循環。這就是爲什麼它在for循環結束時只有一個對象。嘗試替換此代碼。

NSArray * processes = [[UIDevice currentDevice] runningProcesses]; 
runningprocesses = [[NSMutableArray alloc] init]; 
for (NSDictionary * dict in processes){ 
    NSString *process = [dict objectForKey:@"ProcessName"]; 
    [runningprocesses addObject:process]; 
} 

這應該有效。

0

您應該將您的alloc-init聲明移至for循環之外。下面是代碼

runningprocesses = [[NSMutableArray alloc] init]; 
NSArray * processes = [[UIDevice currentDevice] runningProcesses]; 

for (NSDictionary * dict in processes) 
{ 
    NSString *process = [dict objectForKey:@"ProcessName"]; 
    [runningprocesses addObject:process]; 
} 
相關問題