I want to write a dictionary that has custom objects all of the same type into the cache directory. I don’t know what is wrong but nothing is written. writeToFile returns false. This was working when I needed to save just a single user instance but now I need a dictionary. The dictionary keys are strings. The strange thing is initWithCoder and encodeWithCoder aren’t called at all.
I get the cache folder like this
NSString * NSCacheDirectory()
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [paths objectAtIndex:0];
#ifdef DEBUG
NSString *regi = [NSHomeDirectory() stringByAppendingPathComponent: @"/Library/Caches/"];
#endif
return cacheDirectory;
//return [NSHomeDirectory() stringByAppendingPathComponent: @"/Library/Caches/"];
}
I save a dictionary like this:
+(void) saveSharedUsers {
NSString *cacheDir = NSCacheDirectory();
NSFileManager *fm = [[NSFileManager alloc] init];
Boolean success = true;
NSError *error = nil;
if (![fm fileExistsAtPath: cacheDir ])
success = [fm createDirectoryAtPath: cacheDir withIntermediateDirectories: true attributes: nil error: &error];
success = [[User sharedUsers] writeToFile: [NSCacheDirectory() stringByAppendingPathComponent: USER_FILE] atomically: true];
[fm release];
}
User object:
@interface User : NSObject <NSCoding> {
NSString *email;
NSInteger userId;
NSString *name;
NSString *facebookId;
}
@property(nonatomic, copy) NSString *email;
@property(nonatomic, assign) NSInteger userId;
@property(nonatomic, copy) NSString *name;
@property(nonatomic, copy) NSString *facebookId;
...
@end
@implementation User
...
@synthesize email,userId,name, facebookId;
- (void) encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject: self.name forKey:@"name"];
[aCoder encodeObject: self.email forKey:@"email"];
[aCoder encodeObject: self.facebookId forKey:@"facebookId"];
[aCoder encodeInteger: self.userId forKey: @"userId"];
}
- (id) initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self != nil)
{
self.name = [aDecoder decodeObjectForKey: @"name"];
self.email = [aDecoder decodeObjectForKey: @"email"];
self.facebookId = [aDecoder decodeObjectForKey: @"facebookId"];
self.userId = [aDecoder decodeIntegerForKey: @"userId"];
}
return self;
}
...
@end
I’m assuming that
-[User sharedUsers]is an instance of NSDictionary. Then you’ll be writing a plist file to that location, not the archived data.You should try this:
That will archive the objects and write the archived data to disk.
Loading the data is the reverse operation: