我的代码中有一组自定义对象。
我想将此数组写入文档文件夹中的文件中。在这个答案iPhone -我看到我需要实现这个方法的自定义对象的归档数组中:
- (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;
}
我用这个方法调用 write:
-(void) writeArrayToHistoryFile:(NSArray *) array {
NSString *path = [self plistHistoryFile];
NSLog(@"%@", path);
if ([array writeToFile:path atomically:NO]) {
NSLog(@"YES");
} else {
NSLog(@"NO");
}
}
但我在日志上的回答总是“否”,我做错了什么?