我的代码中包含一系列自定义对象。
我想将此数组写入文档文件夹中的文件中。在这个答案中iPhone - archiving array of custom objects我看到我需要实现这个方法:
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (id)initWithCoder:(NSCoder *)aDecoder;
所以我实施了它们:
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.data forKey:@"data"];
[encoder encodeObject:self.nome forKey:@"nome"];
[encoder encodeObject:self.celular forKey:@"celular"];
[encoder encodeObject:self.endereco forKey:@"endereco"];
[encoder encodeObject:self.horaConclusao forKey:@"horaConclusao"];
[encoder encodeObject:self.horaAtendimento forKey:@"horaAtendimento"];
}
- (id)initWithCoder:(NSCoder *)decoder {
self = [super init];
if (self) {
self.data = [decoder decodeObjectForKey:@"data"];
self.nome = [decoder decodeObjectForKey:@"nome"];
self.celular = [decoder decodeObjectForKey:@"celular"];
self.endereco = [decoder decodeObjectForKey:@"endereco"];
self.horaConclusao = [decoder decodeObjectForKey:@"horaConclusao"];
self.horaAtendimento = [decoder decodeObjectForKey:@"horaAtendimento"];
}
return self;
}
在我的代码中我使用这种方法编写:
此代码用于删除旧文件
-(NSString *) plistHistoryFile {
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[nameFile stringByAppendingPathExtension:@"plist"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:path]) {
[filemgr removeItemAtPath:path error:&error];
}
return path;
}
我用这种方法调用了写:
-(void) writeArrayToHistoryFile:(NSArray *) array {
NSString *path = [self plistHistoryFile];
NSLog(@"%@", path);
if ([array writeToFile:path atomically:NO]) {
NSLog(@"YES");
} else {
NSLog(@"NO");
}
}
但是我对日志的回答总是没有,我做错了什么?
答案 0 :(得分:0)
您需要找出错误是什么,但您无法使用-[NSArray writeToFile:atomically:]
获取错误。相反,以这种方式编写文件:
NSError *error;
NSData *data = [NSPropertyListSerialization dataWithPropertyList:array
format: NSPropertyListBinaryFormat_v1_0 options:0 error:&error];
if (!data) {
NSLog(@"failed to convert array to data: %@", error);
return;
}
if (![data writeToFile:path options:NSDataWritingAtomic error:&error]) {
NSLog(@"failed to write data to file: %@", error);
return;
}
NSLog(@"wrote data successfully");