I am developing an iPhone application using Objective-C. I want to access a data member which is of type NSMutableArray of the RootViewController class in another class. I tried making the array static. But I would like to have a non static array. How do I achieve this?
Share
You need two things:
RootViewControllerRootViewController.In a situation where you have (most likely) one
RootViewControllerper application, it makes sense to keep a reference to that object in your application’s delegate. You can get the app delegate like this:In your app delegate class you should add a property called
rootViewControllerthat exposes yourRootViewControllerobject. Now you can write things likeThis satisfies the first requirement. Now, in order to access the object owned by the view controller, you’ll need to add a property to
RootViewController. You didn’t really say what the object is or does, so let’s just call itmyMutableArray. Create areadonlyproperty with that name onRootViewController, and now you’ll be able to write things like this:This will let you do what you want to do.
I have to warn you, though: exposing an
NSMutableArrayis generally not a great idea. The reason is that if you change the contents of that array,RootViewControllerwill have no idea that you’ve done this. So if you were creating, say, a master-detail view, yourRootViewControllerwould not know that you’ve added a new object.It would be better if you wrote methods that let
RootViewControllermodify the array internally. For example, you could have a method namedaddFooObject:that manages the array. Then the view controller will know what you’ve done to it. For access, you could very easily return an immutable, autoreleased copy of the mutable array from your property.