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主要用於存儲用戶首選項,而不是一般數據。我錯過了什麼嗎?提前致謝。