Reputation:
NSString *senderName = [sender currentTitle];
NSLog(@"Text to be Saved = %@",senderName);
[name setObject:senderName forKey:@"key"];
NSString *TextActuallySaved = [name stringForKey:@"key"];
NSLog(@"Text actually Saved = %@", TextActuallySaved);
So I have this code, And when I run it I get this in the console:
appName[19556:f803] Text to be Saved = SCV
appName[19556:f803] Text actually Saved = (null)
So, what did I do wrong? I declared a NSUserDefault object in the header at the @interface like so:
@interface viewController : UIViewController {
NSUserDefaults *name;
}
All this code is in a ViewController as it is getting pushed. So is that why? If so is there a way to get around that? This is seriously bugging me. Any help would be much appreciated. THANKS!
Here is my Init code
- (id)init {
if (self = [super init])
{
name = [NSUserDefaults standardUserDefaults];
}
return self;
}
Upvotes: 0
Views: 51
Reputation: 27147
Unlike most Objects the designated initializer for a UIViewController
is not init
. I see now that you did say that this is a ViewController, sorry I missed it before. The designated initializer for a UIViewController
is either initWithCoder
or initWithFrame
, one of those to will be called for initialization. Which leads to problems, 'where do I put my setup code', this has been discussed on SO before.
In fact I'd wager that if you put NSLog(@"Init");
in your init
method you'd see it's never called. Therefore it can never assign your ivar
.
For simplicity if you are subclassing UIViewController
and want to do initialization that doesn't HAVE to be in an init method the you use viewDidLoad
.
- (void)viewDidLoad{
[super viewDidLoad];
name = [NSUserDefaults standardUserDefaults];
// Do any additional setup after loading the view, typically from a nib.
}
Upvotes: 0
Reputation: 187034
Did you actually set that ivar to a defaults object?
name = [NSUserDefaults standardUserDefaults];
You would typically do such thing in your init method.
Im guessing this because in ObjectiveC nil can have methods called on it, all of what return nil. So if name
is nil, then it will silently fail to save, then call return nil when you try read it back.
Upvotes: 1