2016-05-14 64 views
0

我想在使用NSKeyedArchiver寫入文件的iOS應用程序上保存一些持久數據,並且我想稍後使用NSKeyedUnarchiver檢索此數據。我創建了一個非常基本的應用程序來測試一些代碼,但沒有成功。 下面是我使用的方法:無法使用NSKeyedArchiver/NSKeyedUnarchiver在文件上設置/檢索數據

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    Note *myNote = [self loadNote]; 

    myNote.author = @"MY NAME"; 

    [self saveNote:myNote]; // Trying to save this note containing author's name 

    myNote = [self loadNote]; // Trying to retrieve the note saved to the file 

    NSLog(@"%@", myNote.author); // Always logs (null) after loading data 
} 

-(NSString *)filePath 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent: @"myFile"]; 
    return filePath; 
} 

-(void)saveNote:(Note*)note 
{ 
    bool success = [NSKeyedArchiver archiveRootObject:note toFile:[self filePath]]; 
    NSLog(@"%i", success); // This line logs 1 (success) 
} 

-(Note *)loadNote 
{ 
    return [NSKeyedUnarchiver unarchiveObjectWithFile:[self filePath]]; 
} 

,我使用來測試該代碼如下類:

Note.h

#import <Foundation/Foundation.h> 

@interface Note : NSObject <NSCoding> 

@property NSString *title; 
@property NSString *author; 
@property bool published; 

@end 

Note.m

#import "Note.h" 

@implementation Note 

-(id)initWithCoder:(NSCoder *)aDecoder 
{ 
    if (self = [super init]) 
    { 
     self.title = [aDecoder decodeObjectForKey:@"title"]; 
     self.author = [aDecoder decodeObjectForKey:@"author"]; 
     self.published = [aDecoder decodeBoolForKey:@"published"]; 
    } 
    return self; 
} 

-(void)encodeWithCoder:(NSCoder *)aCoder 
{ 
    [aCoder encodeObject:self.title forKey:@"title"]; 
    [aCoder encodeObject:self.author forKey:@"author"]; 
    [aCoder encodeBool:self.published forKey:@"published"]; 
} 

@end 

我看過類似的例子,使用NSUserDefaults(https://blog.soff.es/archiving-objective-c-objects-with-nscoding),bu t我想將這些數據保存到文件中,因爲據我所知,NSUserDefaults主要用於存儲用戶首選項,而不是一般數據。我錯過了什麼嗎?提前致謝。

回答

0

想想第一次運行應用程序會發生什麼,並且您打電話給loadNote:方法,但還沒有保存任何內容。

行:

Note *myNote = [self loadNote]; 

將導致myNotenil因爲沒有加載。現在想想如何通過其他代碼級聯。

您需要處理這個沒有保存數據的初始情況。

Note *myNote = [self loadNote]; 
if (!myNote) { 
    myNote = [[Note alloc] init]; 
    // Setup the initial note as needed 
    myNote.title = ... 
}