Reputation: 10643
So I have an array of student names. I'm running test data so I'm going through a loop allocating and initializing each student then just throwing it in stuArr
- If I NSLog my Student.h
init() method it will give me the names I would expect but when I try to call them outside of my method I get null values:
- (void)viewDidLoad
{
[super viewDidLoad];
for (int i = 0; i < 5; i++) {
stuArr = [stuArr arrayByAddingObject:[[Student alloc] init]];
id test = [stuArr objectAtIndexedSubscript:i];
NSLog(@"%@", [test stuName]);
}
}
Am I missing something vital here? If need be I can throw in my Student.m File but everything seems fine there.
Upvotes: 1
Views: 472
Reputation: 161
tikhop is right: if you fill an array in a for loop you should initialize NSMutableArray (mutable Array because you are changeing the array in the loop) before you fill it. in the loop you adding objects to the array with [array addObject:id]
.
What [array arrayByAddingObject:id]
does is it creates a copy of the receiving Array and adds the new object to the end.
which means to use that you will need to do something like the following (doesn't make much sense to do that in an for-loop though but maybe it helps to understand):
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *stuArr = [NSArray alloc] init]; //stuArr can be used now
for (int i = 0; i < 5; i++) {
//someCopiedArr is some existing array- arrayByAddingObject will copy someArr and add an object
stuArr = [someArr arrayByAddingObject:[[Student alloc] init]];
id test = [stuArr objectAtIndexedSubscript:i];
NSLog(@"%@", [test stuName]);
}
}
In the end stuArr
will be a copy of someArr
just with the object added to the end.
Upvotes: 1
Reputation: 2087
I guess that you should alloc + init stuArr before this line:
stuArr = [stuArr arrayByAddingObject:[[Student alloc] init]];
Or try to do something like this:
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *mutStudentsArray = [NSMutableArray array];
for (int i = 0; i < 5; i++)
{
[mutStudentsArray addObject:[[Student alloc] init]];
id test = [mutStudentsArray objectAtIndex:i];
NSLog(@"%@", [test stuName]);
}
stuArr = [NSArray arrayWithArray:mutStudentsArray];
}
Upvotes: 5