Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

teengohan

macrumors newbie
Original poster
May 20, 2011
27
0
I have the following code in my viewDidLoad meathod:
Code:
	for (id key in dictionary) {
		NSString *name;
		name = [dictionary valueForKey:@"name"];
		[listOfNames addObject:name];
		NSLog(name);

	}

list of names is declared in the header file as:
Code:
	@interface RootViewController : UITableViewController {
	NSMutableArray *listOfNames;
}
@property (nonatomic, retain) NSMutableArray *listOfNames;
 

@end
For some reason the console output is what I expected, a list of names but no values are being added to the array. I put a breakpoint in at the end of viewDidLoad and the array has zero entries. Does anyone know where i am going wrong here?
 
Where are you creating listOfNames? Declaring a property is declaring a variable: a space to store the object in. It does not create a NSMutableArray object for you. You must create the object somewhere and assign that to the property.
 
Looks like I was misunderstanding a bit of objective c there. I thought it was initialised when I first assigned it values here:
Code:
[listOfNames addObject:name];
is my problem that I have declared the array but not initialised it? If so how do I initialise it? Sorry for newbie question, I'm new to this :p
 
Looks like I was misunderstanding a bit of objective c there. I thought it was initialised when I first assigned it values here:
Code:
[listOfNames addObject:name];
is my problem that I have declared the array but not initialised it? If so how do I initialise it? Sorry for newbie question, I'm new to this :p

Code:
NSMutableArray *listOfNames = [[NSMutableArray alloc] initWithCapacity:[dictionary count]]

If you put this right before your for loop, it should work. You now have initialized (initWithCapacity) the variable so you can add objects to it.
 
Ok, I did that but now I get a yellow warning that the "Local declaration of 'listOfNames' hides instance variable". I ned to be able to access this array after this meathod is done as I need to use its contents in another part of my app, one example is I later use this array to populate a table..
 
Ok, I did that but now I get a yellow warning that the "Local declaration of 'listOfNames' hides instance variable". I ned to be able to access this array after this meathod is done as I need to use its contents in another part of my app, one example is I later use this array to populate a table..

I'm sorry, forgot it was an ivar. The correct code is:

Code:
listOfNames = [[NSMutableArray alloc] initWithCapacity:[dictionary count]];
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.