0

I have an NSMutableArray in my app delegate. I wish to use that mutable array in a different class in my program, as if it were a global variable. How would I do this?

Is it as simple as importing the header and referencing the object?

jscs
  • 63,694
  • 13
  • 151
  • 195
Sandeep Bansal
  • 6,280
  • 17
  • 84
  • 126
  • Does it not make sense to use this as an ivar for your delegate? – Sean May 19 '11 at 16:19
  • possible duplicate of [objective C: use NSMutableArray in different classes](http://stackoverflow.com/questions/5647154/objective-c-use-nsmutablearray-in-different-classes) – jscs May 19 '11 at 17:32
  • Not to mention [NSMutableArray in other Class](http://stackoverflow.com/questions/5516266/) and [Access NSMutableArray from a different Class](http://stackoverflow.com/questions/5240240/). – jscs May 19 '11 at 17:33

2 Answers2

6

Take advantage of the UIApplication singleton:

YourAppDelegate *appDelegate = (YourAppDelegate *)[[UIApplication sharedApplication] delegate];

Then, access your array property like this: appDelegate.yourArrayProperty

albertamg
  • 28,492
  • 6
  • 64
  • 71
2

Make you array a property of your delegate as Sean said

@property(readonly) NSMutableArray *theArray;

Then access the array like this :

((YourAppDelegateClass *)[UIApplication sharedApplication].delegate).theArray
martiall
  • 981
  • 6
  • 7
  • I know this is forever old. However, I had a question. If you set your array to read only wouldnt that defeat the purpose of an NSMutableArray as no view could add to it....making it an NSArray? – Nathan Kellert Jun 27 '13 at 07:10
  • Short answer : No. Long answer : the pointer to the NSMutableArray is read only (ie you can't change the instance of the NSMutableArray) but the array is mutable (and the readonly property can't change that) so you can add/delete items. – martiall Jun 30 '13 at 20:30