I’m trying to do the right thing by not using global variables in my Xcode project. I’ve successfully created a singleton. I have a simple data store which I named “myContactsStore” that contains an array, with each object in the array having only 3 instance variables (name, phoneNum, and eMail). I have no problem creating, modifying, saving etc. the data in the array when I’m executing the view controller that created the array.
My problem is trying to access the data store from another view controller. I’m halfway there, as proven by my ability to print the contents of the entire test array from another view controller by using the following code in a for loop:
NSLog(@"%@", myContactsStore.description);
Here’s the output:
"Mary, 0938420839, PaulDoe@Mac.com",
"John, 9932097372, PaulDoe@Mac.com",
"Mary, 0726756893, RedCat@iwon.com",
"Mary, 8556327199, xxxbct@mac.com",
"John, 0640848317, xxxbct@mac.com"
How do I access just one instance variables? For example, I want to create a read-only array in another view controller that contains just the email addresses of every contact in the “myContactsStore” array. I’ve tried several things, but I’m new at this and I must be missing something very basic.
Thanks for you help and any code example you might have the time to include.
You can stick this to any class to make it a singleton:
Better yet, you can add the class as an ivar of the application delegate, which is a singleton you already have. You can get a reference to it like this:
Then you access the datastore as an ivar on that delegate, and optionally implement one of the several persistence technologies available on iOS, basically plist files through direct file access or NSCoding or even NSUserDefaults (which you shouldn’t but it’s handy for small tasks), Core Data, or SQLite.
If you are using this data store class only to pass data between controllers, you can do so directly instead. Example: