在iPhone SDK中将对象添加到阵列时出现问题

时间:2011-06-24 11:50:15

标签: iphone ios cocoa-touch

我在iPhone SDK中向NSArray添加对象时遇到问题。问题是它只添加了我的NSDictionary的最后一个对象。这是代码:

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"]时,它向我展示了所有进程,但是如果我尝试添加它们,它只会添加最后一个进程。可能会发生什么?

4 个答案:

答案 0 :(得分: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];
}

当我尝试时,这对我有用:]

答案 1 :(得分: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];
}

答案 2 :(得分:0)

您每次都在for循环中尝试分配“runningprocesses”数组。这就是为什么它在for循环结束时只有一个对象。尝试替换此代码。

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

这应该有用。

答案 3 :(得分: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];
}