0

A perhaps basic question regarding a singleton class which I want to have as a "dataController"

I have based most of the singleton implementation on the banans thread: Using a singleton to create an array accessible by multiple views

I am wondering about functions in the singleton class. Before I made the dataController a singelton i hade a function to add a banana to the masterBananaList.

How do I use this function instead of manipulating the array list directly in the viewController that I am in.

I.e how do I use this: (I get warning: dataController hides instance variables)

DataControllerSingleton *dataController= [DataControllerSingleton singleDataController];
[dataController addBananaToList:banana];

Instead of:

DataControllerSingleton *dataController= [DataControllerSingleton singleDataController];
[dataController.masterBananaList addObject:care];

Do i use local or global functions in an Singleton and if I use global how do i use self.masterBananaList which only works for local methods.

Community
  • 1
  • 1
djcj
  • 149
  • 2
  • 15
  • Singleton classes are classes that are designed to ever only have one instance. For the rest, it's exactly the same as a regular class. – Maarten May 15 '13 at 15:17

2 Answers2

3

I could be wrong, but "dataController hides instance variables" suggests to me that you have an instance variable called dataController and that this local variable named dataController is shadowing/hiding the instance variable. Try changing the name of your local variable.

ipmcc
  • 29,581
  • 5
  • 84
  • 147
1

Well, just rename the local variable dataController to something different and you should get rid of the warnings. You may use myDataController or so instead.

I would prefer this one:

DataControllerSingleton *dataController= [DataControllerSingleton singleDataController];
[dataController addBananaToList:banana];

over this one:

DataControllerSingleton *dataController= [DataControllerSingleton singleDataController];
[dataController.masterBananaList addObject:care];

I think it is generally true for all OO languages that accessing a classes data by calling methods is preferred over accessing properties directly. You may argue that Objective-C always generates a proper getter and setter automatically (unless you implement them yourself). And strictly spoken that is accessing though methods. And providing a method addBananaToList: may look like programming overhead, but it provides you with more flexibility on how DataControllerSingleton internally works. In the future you may want to use something different, move the data to the cloud or whatever, instead of holding it in an NSMutableArray. It should not be the external classes business how exactly DataControllerSingleton works internally.

Hermann Klecker
  • 14,039
  • 5
  • 48
  • 71