0

I'm making an iOS app in Xcode 4 that needs to save one NSString variable. Does anyone know if using a .plist file is the best way to do this if so, what code do you need to store and retrive NSStrings?

Any help would be awesome!

justin
  • 104,054
  • 14
  • 179
  • 226
Bastian2025
  • 65
  • 2
  • 6

2 Answers2

4

Best place would be to store it in NSUserDefaults:

[[NSUserDefaults standardUserDefaults] setObject:@"My String" forKey:@"kMyStringKey"];

Then to call it:

lblMyLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"kMyStringKey"];
WrightsCS
  • 50,551
  • 22
  • 134
  • 186
0

there are multiple ways to store an NSString because needs vary. Plist in this case is more than necessary (based on the description).

Option A You could just use: - [NSString writeToURL:atomically:encoding:error:]. in this case, you only need to remember the file URL and encoding you saved it in.

Option B another option would be to save it via NSCoding -- this allows NSString to choose the serialized representation it finds is best, given the string it represents.

justin
  • 104,054
  • 14
  • 179
  • 226
  • 1
    I'm curious why you don't recommend `NSUserDefaults` here. Any info on that? – Robert Karl Oct 13 '12 at 06:23
  • @RobertKarl two reasons: a) it's not specified in the OP that the value *belongs* in user defaults. therefore, i assume it does not belong there. b) using WrightCS's example; that is effectively a glorified/persistent global value. also not safe to assume that is compatible with the OP's needs because there can be only one value for that key. therefore, i don't recommend `NSUserDefaults` as the "best way" to store an arbitrary `NSString`. that the OP suggested a plist file also suggests that a file is more in line with the OP's usage. will dig up a link for point a… – justin Oct 13 '12 at 06:41
  • 1
    @RobertKarl see Peter Hosey's well-worded explanation of when to use and when not to use `NSUserDefaults` here: http://stackoverflow.com/questions/5520797/when-not-to-abuse-nsuserdefaults – justin Oct 13 '12 at 06:45
  • 1
    Thanks, I appreciate it! I may need to edit my apps ;) – Robert Karl Oct 13 '12 at 07:55