0

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?

1
  • because In your code, each time the loop iterates, the runningprocesses array is pointing to a new instance. Commented May 14, 2014 at 10:29

4 Answers 4

2

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 :]

Sign up to request clarification or add additional context in comments.

2 Comments

+1: The only answer that uses initWithCapacity: for NSArray creation
Yes, I'm a "capacity-nazi"... its the only way I can truly trust mutable data on not acting weird.
0

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

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.