When I initialize
self.nsmutableArray = [NSMutableArray array];
in my viewDidLoad method NSMutableArray initialize correctly and i can addObject inside it. But if i skip the above initialization in viewDidLoad method and initialize it in some other methods, NSMutableArray initialize incorrectly and i can not addObject inside it.
Why this behavior. Is it need to be initialized in viewDidLoad always?
I think this is almost a duplicate question. Your issue has little to do with the
NSMutableArrayinitialization and more to do with how you conduct memory management in Objective-C on subclasses ofNSObjectin general.See related post on
NSStrings here. Look at the top answer.If you want the array to last for the lifetime of the class, try:
self.nsmutablearray = [[NSMutableArray alloc] init];Just make sure you release it in the
deallocmethod:[self.nsmutablearray release];Alternatively, you could
@synthesizensmutablearray, but you would still need to handle its release. There are a myriad of ways to address this issue.