开发者

Problem adding objects to array in iPhone SDK

开发者 https://www.devze.com 2023-03-14 23:22 出处:网络
I\'m having a problem with adding objects to an NSArray in iPhone SDK. The problem is that it only adds the last object of my NSDictionary. This is the code:

I'm having a problem with adding objects to an NSArray in iPhone SDK. The problem is that it only adds the last object of my NSDictionary. This is the code:

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

When I NSLog [dict objectForKey:@"ProcessName"] it shows me all the processes but if I try to add them it only adds the last one. What could be happening?


I reedited your code as I would suggest you try instead :

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

This works for me when I try it :]


In your code, each time the loop iterates, the runningprocesses array is pointing to a new instance.

To fix it move your array instantiation outside the for loop:

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

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


You are trying to allocating "runningprocesses" array every time in the for loop. That is why it would have only one object at the end of for loop. Try replacing this code.

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

This should work.


You should move your alloc-init statement outside the for loop. Here is the following code

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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号