Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing data member of RootViewController in another class

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?

like image 854
Neo Avatar asked Dec 14 '22 05:12

Neo


1 Answers

You need two things:

  1. a reference to the RootViewController
  2. a means of getting your variable out of RootViewController.

In a situation where you have (most likely) one RootViewController per application, it makes sense to keep a reference to that object in your application's delegate. You can get the app delegate like this:

AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

In your app delegate class you should add a property called rootViewController that exposes your RootViewController object. Now you can write things like

RootViewController *theRootViewController = appDelegate.rootViewController;

This 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 it myMutableArray. Create a readonly property with that name on RootViewController, and now you'll be able to write things like this:

NSMutableArray *myArray = theRootViewController.myMutableArray;

This will let you do what you want to do.

I have to warn you, though: exposing an NSMutableArray is generally not a great idea. The reason is that if you change the contents of that array, RootViewController will have no idea that you've done this. So if you were creating, say, a master-detail view, your RootViewController would not know that you've added a new object.

It would be better if you wrote methods that let RootViewController modify the array internally. For example, you could have a method named addFooObject: 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.

like image 116
Alex Avatar answered Feb 01 '23 23:02

Alex