0

what is the default saving location of NSCoding protocol?

Also, is there any way to change such a default location to say, the folder where the .app file is located?

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
Kevin
  • 1,469
  • 2
  • 19
  • 28
  • 3
    you should read this docu: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Archiving/Archiving.html#//apple_ref/doc/uid/10000047i – CarlJ Apr 11 '12 at 09:03

1 Answers1

1

You can directly write your encoded object data encoded according NSCoding to a file using NSKeyedArchiver

Like this:

BOOL result = [NSKeyedArchiver archiveRootObject:yourObject toFile:filename];

With filename you can choose your file location (you may set it to the documents directory if you are on iOS).

EDIT 1: If you'd like to store in into NSUserDefault... do:

NSData *yourObjectAsNSData = [NSKeyedArchiver archivedDataWithRootObject:yourObject];
[[NSUserDefaults standardUserDefaults] setObject:yourObjectAsNSData forKey:@"aKey"]
Jonas Schnelli
  • 9,965
  • 3
  • 48
  • 60
  • What if I use archivedDataWithRootObject:object ? Does the toFile: parameter still apply? I tried it but couldn't get it to work. Thanks! – Kevin Apr 11 '12 at 11:06
  • Tried: NSString *path = @"file"; [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archiveRootObject:array toFile:path] forKey:@"savedArray"]; which leads to an EXC_BAD_ACCESS error + warning that I am making a pointer from integer without a cast.. – Kevin Apr 11 '12 at 11:12
  • 1
    wrong wrong. you try to store the BOOL "result" in your NSUserDefaults. That will crash!. I'll update my answer .. – Jonas Schnelli Apr 11 '12 at 11:17
  • Thank you for your answer, that is what I am currently doing. What I would like to know is if it is possible to know where the data is being saved on disk, and if I can change that path to the application path, using the code as per your edit 1? – Kevin Apr 11 '12 at 12:02
  • 1
    Nope. When using NSUserdefaults the sore and the store location will be given by the OS. So, if you'd like to have a different "file" you need to write the data directly to a file as shown in the first example. – Jonas Schnelli Apr 11 '12 at 12:25
  • Ok, thanks.. Just a quick question then, if I use the first method example that you gave me, how would I go about unarchieving the data? I found : [NSKeyedUnarchiver unarchiveObjectWithData:] and [NSKeyedUnarchiver unarchiveObjectWithFile:] Is there a way that I can use them both together? Cheers ! – Kevin Apr 11 '12 at 12:42