2

I have an app that needs access to a set of user data that can't be stored on disk. My typical approach in the past would be to create a singleton to hold this data with a concurrent queue for each property to make data reads/writes thread safe.

What I am wondering is if there is a way to do this without the use of Singletons or storing a reference to my user data in my AppDelegate.

Gabriel
  • 31
  • 1
  • What do you have against writing to files? What do you have against singletons? – Ian MacDonald Jan 27 '15 at 21:33
  • One of the requirements is not saving data to disk for security reasons. – Gabriel Jan 27 '15 at 21:47
  • @Rob I am trying to avoid the use of globally accessible data. Trying to come up with a way to use DI instead. Maybe a framework like Typhoon will work. – Gabriel Jan 27 '15 at 21:51
  • @rob Ian MacDonald asked what I had against writing things to disk. – Gabriel Jan 27 '15 at 21:52
  • I might refer you to http://stackoverflow.com/a/162090/1271826, which quotes http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/ – Rob Jan 27 '15 at 22:49
  • @rob So essentially creating getting rid of the static sharedInstance and saving a copy of the class in the App Delegate. – Gabriel Jan 27 '15 at 22:53
  • And passing it to objects that need it, making the relationship explicit, making it easier to unit test, etc. Notably, not letting any any old object sneak in and use/mutate it, but passing reference to those classes that really need it. – Rob Jan 27 '15 at 22:58

1 Answers1

-1

NSUserDefaults sounds like what you're looking for. According to Apple's documentation, "The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an application to customize its behavior to match a user’s preferences." You can use NSUserDefaults in a global manner.

To do this, you need to first create an NSUserDefaults object:

NSUserDefaults *myAppDefaults = [NSUserDefaults myAppDefaults];

To save data to the defaults system, you would do something similar to the line below:

[standardDefaults setObject:@"Smith" forKey:@"lastName"];

Finally, you can retrieve your data from the defaults system by storing it in a variable. The line below shows how to set an NSString to be the value you originally stored:

NSString *lastName = [standardDefaults stringForKey:@"lastName"];
narner
  • 2,908
  • 3
  • 26
  • 63
  • How is this better than singletons? If anything, it's much, much worse. It doesn't address the issues that one might have with singletons, but rather just introduces a bunch of other issues. – Rob Jan 27 '15 at 21:36
  • In addition, I can't store user information to disk. – Gabriel Jan 27 '15 at 21:45