写一个自定义对象数组

我在我的代码中有一组自定义对象。写一个自定义对象数组

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

}

}

但我对日志的回应总是NO,我做错了什么?

回答:

你需要找出错误是什么,但是你不能使用-[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");

以上是 写一个自定义对象数组 的全部内容, 来源链接: utcz.com/qa/257196.html

回到顶部