我有一个“DataStorage”类,我希望使用NSCoding协议来保存数据。但是,当尝试添加到该类的数组时,
[DataStorage sharedData].firstNameArray addObject:firstName:];
在DataStorage类中查看断点时,它显示数组为“nil”值
这是类实现......
#import "DataStorage.h"
@implementation DataStorage
@synthesize firstNameArray = _firstNameArray;
@synthesize surnameArray = _surnameArray;
@synthesize companyArray = _companyArray;
@synthesize positionArray = _positionArray;
@synthesize emailArray = _emailArray;
@synthesize mobileArray = _mobileArray;
@synthesize productArray = _productArray;
+ (instancetype)sharedData {
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [self loadInstance];
});
return sharedInstance;
}
- (instancetype)initWithCoder:(NSCoder *)decoder
{
self = [self init];
if (self) {
_firstNameArray = [decoder decodeObjectForKey:@"DataStorageFirstNameKey"];
_surnameArray = [decoder decodeObjectForKey:@"DataStorageSurnameKey"];
_companyArray = [decoder decodeObjectForKey:@"DataStorageCompanyKey"];
_positionArray = [decoder decodeObjectForKey:@"DataStoragePositionKey"];
_emailArray = [decoder decodeObjectForKey:@"DataStorageEmailKey"];
_mobileArray = [decoder decodeObjectForKey:@"DataStorageMobileKey"];
_productArray = [decoder decodeObjectForKey:@"DataStorageProductKey"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:_firstNameArray forKey:@"DataStorageFirstNameKey"];
[encoder encodeObject:_surnameArray forKey:@"DataStorageSurnameKey"];
[encoder encodeObject:_companyArray forKey:@"DataStorageCompanyKey"];
[encoder encodeObject:_positionArray forKey:@"DataStoragePositionKey"];
[encoder encodeObject:_emailArray forKey:@"DataStorageEmailKey"];
[encoder encodeObject:_mobileArray forKey:@"DataStorageMobileKey"];
[encoder encodeObject:_productArray forKey:@"DataStorageProductKey"];
}
+ (NSString*)filePath
{
static NSString* filePath = nil;
if (!filePath) {
filePath =
[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
stringByAppendingPathComponent:@"datastorage"];
}
return filePath;
}
+ (instancetype)loadInstance
{
NSData* decodedData = [NSData dataWithContentsOfFile: [DataStorage filePath]];
if (decodedData) {
DataStorage * dataStorage = [NSKeyedUnarchiver unarchiveObjectWithData:decodedData];
return dataStorage;
}
return [[DataStorage alloc] init];
}
- (void)save
{
NSData* encodedData = [NSKeyedArchiver archivedDataWithRootObject: self];
[encodedData writeToFile:[DataStorage filePath] atomically:YES];
}
@end
答案 0 :(得分:1)
首先,_firstNameArray
应该是一个可变数组,但是从[decoder decodeObjectForKey:@"DataStorageFirstNameKey"];
得到的数组不可变,所以你必须创建一个。
其次,当您第一次使用该实例时,没有文件,因此您将在nil
中获得_fileNameArray
,此时,您应该创建一个空的可变数组,以便您可以添加项目在它。
- (instancetype)initWithCoder:(NSCoder *)decoder
{
self = [self init];
if (self) {
_firstNameArray = [[decoder decodeObjectForKey:@"DataStorageFirstNameKey"] mutableCopy];
if (!_firstNameArray) {
_firstNameArray = [NSMutableArray array] ;
}
}
return self;
}
其他属性也是如此。