Reputation: 462
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?
Upvotes: 0
Views: 2129
Reputation: 1377
I think this is almost a duplicate question. Your issue has little to do with the NSMutableArray
initialization and more to do with how you conduct memory management in Objective-C on subclasses of NSObject
in general.
See related post on NSString
s 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 dealloc
method:
[self.nsmutablearray release];
Alternatively, you could @synthesize
nsmutablearray, but you would still need to handle its release. There are a myriad of ways to address this issue.
Upvotes: 1
Reputation: 42542
You don't need to initialize a NSMutableArray in your viewDidLoad message. In fact your NSMutableArray has no knowledge of the context in which it is being initialized.
I would investigate the specifics of the problems you are having when you try to subsequently add objects to the array.
Upvotes: 0