0

I have a class, User, that has an NSMutableArray that stores custom NSObjects. I only want one of these to ever be instantiated throughout the entire app, and I would like to be able to call methods on it in each ViewController for getting and setting. My problem is that I don't know how to call the methods so they apply to this one instance, instead of creating a new one each time. I'm new to objective-c, so the learning curve makes me feel I'm missing something a bit obvious. I've been working on this all day and am at a wit's end. Is there a good solution to my dilemma? Should I use a singleton class?

(If it helps, the class User is basically a class that stores a to-do list for each user that uses my app. The custom NSObjects are to-do items. There's probably a better storage method that should be used here, but I'm not sure what it is.)

RandomPleb
  • 424
  • 1
  • 5
  • 20
  • You should use the singleton pattern. Check out http://stackoverflow.com/a/7569010/988260 and http://www.galloway.me.uk/tutorials/singleton-classes/ – TylerP Aug 18 '14 at 03:26

1 Answers1

2

RandomPleb it sounds like what you're looking for is a Singleton. http://en.wikipedia.org/wiki/Singleton_pattern. I also think this question has been answered before so search around on SO.

Laymen's terms; you create a static reference to the class that you only want one of inside that class, then make a static method in the following way:

//call this from classes that want to modify it

public static getsharedinstance()
{
    if(the static instance of this class does not exist){
        instantiate instance;
    }

return this classes static instance..
}

Hope this helps (and if this is wrong, I hope someone can correct me)

Also in regards to your storing objects, I think NSMutableArray is fine unless it is a very big persistent list where each task has many properties in which case maybe using CoreData would be better.

Fenix

Fenix
  • 188
  • 10
  • Nice answer. A small fix: `return that instance` should be outside the `if` scope. Itherwise you return it only when the instance doesn't exist. – FreeNickname Aug 18 '14 at 03:34
  • ^ Thanks. And also thanks for the code formatting. You are right! Edited to show fix – Fenix Aug 18 '14 at 03:53