0

I am using AFNetworking 2.0 and Mantle in order to connect to an API and return a user account.

My plan is to call the function that gets the user data in the application:didFinishLaunchingWithOptions: method. I will then encode the data and save the user into NSUserDefaults

Is this the best way to approach this task? What alternatives are there? (I'd like to stay away from creating singletons)


UPDATE

Some code to maybe help show what I am thinking in my head:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

NSData *encodedUserData = [defaults objectForKey:@"currentUser"];
if (encodedUserData) {
    self.currentUser = [NSKeyedUnarchiver unarchiveObjectWithData:encodedUserData];
} else {
    NSLog(@"No current user");
    // Show login ViewController
}
Community
  • 1
  • 1
Hodson
  • 3,438
  • 1
  • 23
  • 51

2 Answers2

0

If you are going to get the user account every time user launches the app, then you don't need to store it in NSUserDefaults. Just use a singleton or static object to store it as your model object type.

static Account *_userAccount = nil;
+ (Account*)userAccount {
    return _userAccount;
}
+ (void)setUserAccount:(Account*)account {
    _userAccount = account;
}
dadalar
  • 635
  • 3
  • 8
  • Sorry, I think I maybe didn't word the question in the best way but I have just added a little code snippet which maybe helps explain it a bit better. – Hodson Oct 09 '14 at 11:45
0

You can use NSUserDefaults for this purpose and can access it through out application.

// to save data in userdefaults

[[NSUserDefaults standardUserDefaults] setObject:@"your object" forKey:@"your key"];
[[NSUserDefaults standardUserDefaults] synchronize];


// for getting saved data from User defaults

NSData *encodedUserData = [[NSUserDefaults standardUserDefaults] objectForKey:@"your key"];
if (encodedUserData) {
    self.currentUser = [NSKeyedUnarchiver unarchiveObjectWithData:encodedUserData];
} else {
    NSLog(@"No current user");
    // Show login ViewController
} 
Hodson
  • 3,438
  • 1
  • 23
  • 51