0

I have a question about NSUserDefault. Currently, i wanna write a function which save the favorite school into a list.

I have school name and school Id. So each time I save, school name + school id will be 1 dictionary object.

Then I save into NSUserDefault base on the id as key. I want to know the number of objects I saved into NSUserDefault. Or How can I get all of the objects out of NSUserDEfault since each of my key is different. Please help me out. below is my code:

NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];


NSMutableDictionary *schools = [[NSMutableDictionary alloc] init];
[schools setObject:schoolName forKey:kSchoolName];
[schools setObject:schoolID forKey:kSchoolID];

[userDefault setObject:schools forKey:schoolID];
user1035877
  • 249
  • 1
  • 5
  • 15
  • 1
    In such cases, I find it easier to store an entire array in NSUserDefauts like "favourite_schools" or something and use it – govi Mar 13 '12 at 11:00
  • Saving an array to `NSUserDefaults` is perfectly explained here http://stackoverflow.com/a/2315972/1141395 . Its much easier and you don't have to save any keys you used for saving. If your objects have also arrays which should be saved remember to add `NSCoding` to the objects inside the array too. – Alex Cio Jan 30 '15 at 16:10

2 Answers2

13

How many objects are you storing? Maybe this isn't the best use for NSUserDefaults.

But to directly answer your question:

NSUInteger count = 
  [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] count];
Alex Cio
  • 6,014
  • 5
  • 44
  • 74
Stephen Darlington
  • 51,577
  • 12
  • 107
  • 152
  • Nice answer, didn't know its possible to print all saved items. – Alex Cio Jan 30 '15 at 16:06
  • I get a 19-digit number when I try to print using po [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] count] in the debug screen – SimonKravis Apr 30 '21 at 01:58
  • If I create a dictionary from standardUserDefaults with NSDictionary * defaultDict = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]; and view it in variables window it shows 275 key/value pairs including general Mac ones like AppleLocale. – SimonKravis Apr 30 '21 at 02:06
  • 19 digit number was an address... casting to NSInteger gave 275 – SimonKravis Apr 30 '21 at 02:11
-2

You would want to use a same key to store your schools dictionary.I mean,

[userDefault setObject:schools forKey:@"Schools List"];

Then to retrieve it

    NSDictionary *schools = [userDefault ObjectforKey:@"Schools List"];
   [[schools allkeys]count];

That will give you the count.

Vignesh
  • 10,205
  • 2
  • 35
  • 73
  • The question was, how to get a list of all items inside `NSUserDefaults` and not how to save and load a single object. This is offtopic. – Alex Cio Jan 30 '15 at 16:12