2012-07-30 109 views
1

我在我的代碼中有一組自定義對象。寫一個自定義對象數組

我想將此數組寫入文檔文件夾中的文件。在這個答案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,我做錯了什麼?

回答

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"); 
相關問題