roof
roof

Reputation: 450

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

Upvotes: 4

Views: 20732

Answers (3)

Mark McCorkle
Mark McCorkle

Reputation: 9414

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

Upvotes: 0

Bug
Bug

Reputation: 93

try this

     for(categoria *cat in categoria){

        [self.categoriasArray addObject:cat];
        // check you go here or not
    }

Upvotes: 2

sch
sch

Reputation: 27506

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++) {
    // ...
}

Upvotes: 7

Related Questions