1

我的代码中有一组自定义对象。

我想将此数组写入文档文件夹中的文件中。在这个答案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");
  }
}

但我在日志上的回答总是“否”,我做错了什么?

4

1 回答 1

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");
于 2012-07-30T19:19:11.313 回答