如何保存/读取填充了我为其创建类的对象的NSMutableArray?
这就是我到目前为止......(其中'ObjectA'代表我的类,'objects'是一个包含许多'ObjectA'实例的数组)
//Creating a file
//1) Search for the app's documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//2) Create the full file path by appending the desired file name
NSString *documentFileName = [documentsDirectory stringByAppendingPathComponent:@"save.dat"];
//Load the array
objects = [[NSMutableArray alloc] initWithContentsOfFile: _documentFileName];
if(objects == nil)
{
//Array file didn't exist... create a new one
objects = [[NSMutableArray alloc]init];
NSLog(@"Did not find saved list, Created new list.");
}
else
{
NSLog(@"Found saved list, Loading list.");
}
这将加载一个数组(如果存在)。如果数组填充了像NSNumbers这样的属性类型对象,我就可以使用它。如果我用自己的对象填充它,它会崩溃!这是错误:(其中'objectAInt'是属于'ObjectA'的私有int)
-[__NSCFNumber objectAInt]: unrecognized selector sent to instance 0x15d417f02013-11-19 17:28:58.645 My Project[1791:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber objectAInt]: unrecognized selector sent to instance 0x15d417f0'
我需要做什么才能让我的类'ObjectA'使用保存/读取过程,就像使用NSNumbers和其他类型(id)的NS对象一样?
谢谢!
P.S。我的类实现并符合NSCoding。如果需要更多信息,请不要犹豫! :)
编辑 - 这是我的ObjectA(每个请求)(它是NSObject的子类)
//
// ObjectA.m
// My Project
//
// Created by Will Battel on 8/8/13.
//
//
#import "ObjectA.h"
@implementation ObjectA
@synthesize objectAString, objectAString2, objectAString3, objectAInt;
-(id)initWithName:(NSString *)_objectAString{
self = [super init];
objectAString = _objectAString;
objectAInt = 2;
objectAString3 = @"$0.00";
return self;
}
-(id)initWithCoder:(NSCoder *)decoder {
self = [super init];
if (self) {
NSLog(@"Decoding");
[self setObjectAString:[decoder decodeObjectForKey:@"objectAStringKey"]];
[self setObjectAString2:[decoder decodeObjectForKey:@"objectAString2Key"]];
[self setObjectAString3Price:[decoder decodeObjectForKey:@"objectAString3Key"]];
[self setobjectAInt:[decoder decodeIntForKey:@"objectAIntKey"]];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)encoder {
NSLog(@"Encoding");
[encoder encodeObject:objectAString forKey:@"objectAStringKey"];
[encoder encodeObject:objectAString2 forKey:@"objectAString2Key"];
[encoder encodeObject:objectAString3 forKey:@"objectAString3Key"];
[encoder encodeInt:objectAInt forKey:@"objectAIntKey"];
}
@end
答案 0 :(得分:1)
由于数组包含符合NSCoding的对象,您可以使用编码方法,例如......
- (NSMutableArray *)instancesFromArchive {
// compute documentFileName using your original code
if ([[NSFileManager defaultManager] fileExistsAtPath:documentFileName]) {
return [NSKeyedUnarchiver unarchiveObjectWithFile:documentFileName];
} else {
return [NSMutableArray array];
}
}
// archives my array of objects
- (BOOL)archiveInstances {
// compute documentFileName using your original code
return [NSKeyedArchiver archiveRootObject:self.objects toFile:documentFileName];
}
答案 1 :(得分:0)
NSNumber类符合NSCoding标准。你自己的对象符合NSCoding吗?