2016-05-14 11 views
0

NSKeyedArchiverを使用してファイルに書き込むiOSアプリケーションの永続データを保存しようとしましたが、NSKeyedUnarchiverを使用してこのデータを後で取得します。私はいくつかのコードをテストするための非常に基本的なアプリケーションを作成しましたが、成功しませんでした。ファイルにNSKeyedArchiver/NSKeyedUnarchiverを使用してデータを設定/取得できません

#import <Foundation/Foundation.h> 

@interface Note : NSObject <NSCoding> 

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

@end 

Note.m

Note.h

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

を次のように私はこのコードをテストするために使用していたクラスがある:ここでは は、私が使用していた方法です

#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 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 = ... 
} 
関連する問題