NSMutableArray addObject not working

Objective CNsmutablearray

Objective C Problem Overview


I have declared an NSMutableArray *categories in my view controller .h file, and declared a property for it.

In the parser:foundCharacters: method of the NSXMLParser delegate in my .m file, I have this code:

-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string  
{  
    if (elementFound)  
    {  
        element = string;  
        [self.categories addObject:element];  
    }  
}

But when I hover over the [self.categories addObject:element] line after stepping into it in debug mode, XCode tells me the size is 0x0, 0 objects. There are 3 elements in my XML file so 3 items should be in the array.

I'm missing something really obvious and I can't figure out what.

Objective C Solutions


Solution 1 - Objective C

The "0x0" part is a memory address. Specifically, "nil", which means your mutable array doesn't exist at the time this is being called. Try creating it in your -init method:

categories = [[NSMutableArray alloc] init];

Don't forget to release it in your -dealloc.

Solution 2 - Objective C

Initialize an empty array using

categories = [NSMutableArray array];

The array class method are autoreleased so no need to release.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjoecView Question on Stackoverflow
Solution 1 - Objective CJoshua NozziView Answer on Stackoverflow
Solution 2 - Objective CiamVishal16View Answer on Stackoverflow