user2007547
user2007547

Reputation: 75

NSUserdefaults multiple data types for one key

After reading from various answers I have come to know that NSUserDefaults can save multiple datatypes for one key. But what I cannot find is if

[NSUserDefaults standardUserDefaults] removeObjectForKey:"someKey"];

removes all objects of all data types associated with that key?

Upvotes: 2

Views: 1844

Answers (6)

FlavienSi
FlavienSi

Reputation: 156

You cannot store different kind of objects for one key.

If you set an object for a key it will erase the old one.

But, if your are searching for a way to store multiple data for one key, you can store a NSDictionary.

Ex :

MyObject *obj = [[MyObject alloc] init];
NSString *otherType = @"mystring";

NSDictionary *multipleData = @{ @"key1" : obj , @"key2" : otherType}

[[NSUserDefaults standardUserDefaults] setObject: multipleData forKey:@"multipleData"];
[[NSUserDefaults standardUserDefaults] synchronize];

And if you want to remove it :

[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"multipleData"];
[[NSUserDefaults standardUserDefaults] synchronize];

Upvotes: 3

hsh
hsh

Reputation: 1

NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
NSString *yourDomain = [[NSBundle mainBundle] bundleIdentifier];
[userDefault removePersistentDomainForName:yourDomain];

Here. if u want to reset.

Upvotes: 0

Sunny Shah
Sunny Shah

Reputation: 13020

    NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];

Upvotes: 0

Hless
Hless

Reputation: 3316

You cannot store multiple objects under one key. NSUserDefaults acts just like a NSDictionary. When you set an object for a specific key you overwrite the old object. So removeObjectForKey: just removes one object/value; the one you had stored under that key.

Upvotes: 1

Rashad
Rashad

Reputation: 11197

Yes it does.

Your data may be anything an array or dictionary or simple int. This command will remove that data.

As iPatel suggested. You need to call:

[[NSUserDefaults standardUserDefaults] synchronize];

After adding or deleting any data. Hope this helps.. :)

Upvotes: 1

iPatel
iPatel

Reputation: 47049

Do you call

[[NSUserDefaults standardUserDefaults] synchronize];

after delete all the data of the key and also might be you can not store multiple data on single key, it's return new one that inserted to last. ?

Read official documentation of removeObjectForKey of NSUserDefaults.

Upvotes: 0

Related Questions