Reputation: 399
Nsuserdefault key returns "(null)" on initial run after installation. How can i check a key exist or not. I have refferred many links ,it say to check It is nill or not. But it didn't worked.
enter code here
- (NSString *)getTalkText
{
NSString *storedUsername = [[NSUserDefaults standardUserDefaults] objectForKey:PERS_STORED_TalkText];
return storedUsername;
}
if(![[[AppManager sharedManager] getTalkText]isEqualToString:@""] || [[AppManager sharedManager]getTalkText]!=nil)
{
self.talkTextView.text=[[AppManager sharedManager]getTalkText];
}
Upvotes: 1
Views: 880
Reputation: 1915
This is the simplest way to check if a particular value for a key is present of not
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSObject * object = [userDefaults objectForKey:@"your_key"];
if(object != nil){
NSLog(@"Object is not nil");
//do your operations here
}else{
NSLog(@"Object is nil");
}
Upvotes: 1
Reputation: 159
It should definitely return nil if there is no object in NSUserDefaults. Even more if it's just after installation, it should only contain some Apple keys (e.g. AppleLanguages). You can inspect it's contents by adding this line somewhere in your [UIApplicationDelegate application:didFinishLaunchingWithOptions:] method:
NSLog(@"%@", [NSUserDefaultsstandardUserDefaults].dictionaryRepresentation);
If you want to just add a default value, please consider using [NSUserDefaults registerDefaults] method as described here: What is the use of -[NSUserDefaults registerDefaults:]?
Upvotes: 0
Reputation: 17186
you have not check the conditions in correct way. Do it by below way:
if([[AppManager sharedManager] getTalkText]!=nil && [[[AppManager sharedManager] getTalkText] length] > 0)
{
// Do the rest
}
Upvotes: 1
Reputation: 10959
if(([[NSUserDefaults standardUserDefaults] objectForKey:@"YOUR_KEY"]) != (id)[NSNull null] || [([[NSUserDefaults standardUserDefaults] objectForKey:@"YOUR_KEY"]) length] != 0)) {
// value available
}
else{
// null
}
Upvotes: 0