Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add objects to NSMutableArray

I'm trying to add objects to NSMutableArray (categoriasArray), but its not done by the iterator:

@synthesize categoriasArray;

for (int i = 0; i < [categories count]; i++) {

        categoria *cat = [[categoria alloc] initWithDictionary:[categories objectAtIndex:i]]; 
        [self.categoriasArray addObject:cat]; 
        cat=nil;

    }

After the for iterator, categoriasArray has 0 objects.

Many thanks

like image 916
roof Avatar asked Jan 18 '23 03:01

roof


1 Answers

Check that the array is not nil before the loop starts:

NSLog(@"%@", self.categoriasArray); // This will output null

for (int i = 0; i < [categories count]; i++) {
    // ...
}

What you should understand is that synthesizing the property categoriasArray doesn't initialize it, it just generates the setter and the getter methods. So, to solve your problem, initialize the array before the loop, (or in the init method of your class):

self.categoriasArray = [[NSMutableArray alloc] init];

The other possibility is that categories is itself nil or doesn't contain any items. To check that, add NSLogs before the loop:

NSLog(@"%@", self.categoriasArray); 
NSLog(@"%@", categories); 
NSLog(@"%d", [categories count]); 

for (int i = 0; i < [categories count]; i++) {
    // ...
}
like image 200
sch Avatar answered Jan 25 '23 14:01

sch