4

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

roof
  • 450
  • 3
  • 13
  • 20

3 Answers3

7

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++) {
    // ...
}
sch
  • 27,436
  • 3
  • 68
  • 83
2

try this

     for(categoria *cat in categoria){

        [self.categoriasArray addObject:cat];
        // check you go here or not
    }
Bug
  • 93
  • 10
0

I would advise getting in the habit of initializing your arrays with autorelease formatting such as the following.This is not only less to type but also good practice for mem management purposes. Of course if you are using ARC then both will work. This goes the same for NSString and many others (i.e. self.categoriasString = [NSMutableString string];)

self.categoriasArray = [NSMutableArray array];

Afterword you can add objects to that array by calling [self.categoriasArray addObject:cat];

Mark McCorkle
  • 9,349
  • 2
  • 32
  • 42