0

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?

2
  • What are "SOME OTHER METHODS" ? Commented May 20, 2011 at 13:29
  • 1
    You may want to review the Objective-C Primer. Commented May 20, 2011 at 13:40

2 Answers 2

1

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 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 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.

Sign up to request clarification or add additional context in comments.

1 Comment

You did not get my point. I know how to initialize something... Maybe trying to understand iOS platform a bit.
0

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.

1 Comment

Thanks for your reply. This is weired to me but now i am sure that I don't need to initialize in viewDidLoad. Maybe something else I am not getting here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.