2011-07-14 50 views
0

我想寫一個具有所有相同類型的自定義對象的字典到緩存目錄中。我不知道什麼是錯,但沒有寫。 writeToFile返回false。當我需要保存一個用戶實例時,這是行得通的,但現在我需要一本字典。字典鍵是字符串。奇怪的是initWithCoderencodeWithCoder根本沒有被調用。無法將字典寫入緩存

我得到這樣

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/"]; 
} 

緩存文件夾中保存我這樣一個字典:

+(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]; 
} 

用戶對象:

@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 

回答

1

我假設-[User sharedUsers]是NSDictionary的實例。然後你將寫一個plist文件到那個位置,而不是存檔的數據。

你應該試試這個:

NSData *archivedUsers = [NSKeyedArchiver archivedDataWithRootObject:[User sharedUsers]]; 
[archivedUsers writeToFile: [NSCacheDirectory() stringByAppendingPathComponent: USER_FILE] atomically: true]; 

這將歸檔的對象和歸檔數據寫入磁盤。

加載的數據是反向操作:

NSDictionary *users = [NSKeyedUnarchiver unarchiveObjectWithData:archivedUsers]; 
+0

感謝它的工作。我實際上忘記了使用'writeToFile'與使用'NSKeyedArchiver'做不同。 –

1

您可以嘗試使用文檔目錄。 到文件目錄的路徑可以通過

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 

訪問然後,你可以再做一次stringByAppendingPathComponent到documentsDirectory。