1
我有一个对象数组,我想保存为一个文件并重新加载到我的应用程序。它正在保存文件(其中包含一些数据),但我无法将其读回到NSMutable Array中。无法获取NSData到NSMutableArray
的对象是符合NSCoding协议模型:
@implementation myModel
@synthesize name;
@synthesize number;
-(void) encodeWithCoder: (NSCoder *) encoder
{
[encoder encodeObject:name forKey:@"name"];
[encoder encodeInteger:number forKey:@"number"];
}
-(id) initWithCoder: (NSCoder *) decoder
{
name = [decoder decodeObjectForKey:@"name"];
number = [decoder decodeIntegerForKey:@"number"];
return self;
}
@end
所以我创建这些对象的数组,然后我将它保存...
- (void) saveMyOptions {
// Figure out where we're going to save the app's data files
NSString *directoryPath = [NSString stringWithFormat:@"%@/Library/Application Support/MyAppDir/", NSHomeDirectory()]; // points to application data folder for user
// Figure out if that directory exists or not
BOOL isDir;
NSFileManager *fileManager = [[NSFileManager alloc] init];
[fileManager fileExistsAtPath:directoryPath isDirectory:&isDir];
// If the directory doesn't exist, create it
if (!isDir)
{
[fileManager createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:NULL];
}
// Assemble everything into an array of objects with options
NSMutableArray *savedPreferences = [[NSMutableArray alloc] init];
myModel *saveOptions = nil;
for (int i; i < [otherArray count]; i++)
{
saveOptions = [[myModel alloc] init];
[saveOptions setName:@"Some String"];
[saveOptions setNumber:i];
[savedPreferences addObject:saveOptions];
saveOptions = nil;
}
// Actually save those options into a file
NSData* saveData = [NSKeyedArchiver archivedDataWithRootObject:savedPreferences];
NSString *fileName = [NSString stringWithFormat:@"%@filename.stuff", directoryPath];
NSError *error = nil;
BOOL written = [saveData writeToFile:fileName options:0 error:&error];
if (!written)
{
NSLog(@"Error writing file: %@", [error localizedDescription]);
}
}
所以,现在我试着将该数据加载回数组中。这是我认为它崩溃的地方...
- (NSMutableArray *) loadOptions {
// Create file manager object
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSData *saveData = nil;
// Find user directory path
NSString *directoryPath = [NSString stringWithFormat:@"%@/Library/Application Support/MyAppDir/", NSHomeDirectory()]; // points to application data folder for user
// Assign file name
NSString *fileName = [NSString stringWithFormat:@"%@filename.stuff", directoryPath];
// Create options array
NSMutableArray *myOptions = nil;
// If the file exists, fill the array with options
if ([fileManager fileExistsAtPath:fileName])
{
saveData = [NSData dataWithContentsOfFile:fileName];
myOptions = [NSKeyedUnarchiver unarchiveObjectWithData:saveData];
}
NSLog(@"%lu", [myOptions count]); // This ALWAYS reports 0!
NSLog(@"%lu", [saveData length]); // This reports a value of 236;
return myOptions;
}
有人能指点我的方向,我要去哪里错了吗?我throughly困惑:-(
提前感谢!
超肯定是它的一部分。谢谢你!第二部分是因为,像一个白痴一样,当我循环使用我想要保存的对象来填充数组时,我没有分配i = 0。因此,循环从未跑,因为我是零...很好。非常感谢你的帮助! – 2012-03-16 01:42:37
甚至没有看到缺少'我'分配。 – 2012-03-16 18:02:14