2010-09-08 14 views
34

mi aplicación para iPad tiene una función de descarga pequeña, para la cual deseo agregar los datos usando un NSFileHandle. El problema es que la llamada de creación solo devuelve identificadores de archivos nulos. ¿Cual podría ser el problema? Aquí está el tres líneas de código que se supone que crear mi identificador de archivo:NSFileHandle fileHandleForWritingAtPath: return null!

NSString *applicationDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
self.finalPath = [applicationDocumentsDirectory stringByAppendingPathComponent: self.fileName]; 
NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath]; 

he comprobado la ruta del archivo, y pude ver nada malo.

TYIA

Respuesta

83

fileHandleForWritingAtPath no es una llamada “creación”. La documentación establece explícitamente: "Valor devuelto: el manejador de archivo inicializado, o nil si no existe ningún archivo en la ruta" (énfasis añadido). Si desea crear el archivo si no existe, habría que usar algo como esto:

NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath]; 
if(output == nil) { 
     [[NSFileManager defaultManager] createFileAtPath:self.finalPath contents:nil attributes:nil]; 
     output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath]; 
} 

Si desea anexar al archivo si ya existe, usar algo como [output seekToEndOfFile]. Su código completo sería entonces el siguiente aspecto:

NSString *applicationDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
self.finalPath = [applicationDocumentsDirectory stringByAppendingPathComponent: self.fileName]; 
NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath]; 
if(output == nil) { 
     [[NSFileManager defaultManager] createFileAtPath:self.finalPath contents:nil attributes:nil]; 
     output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath]; 
} else { 
     [output seekToEndOfFile]; 
} 
+0

Mi archivo existe en "/ var/mobile/Contenedores/datos/aplicaciones/E914726C-34B7-4B92- A740-90E31131D75E/Library/Caches/"pero todavía estoy obteniendo nil. – Nilesh

0

Obtener documentos ruta del directorio

+(NSURL *)getDocumentsDirectoryPath 
{ 
    return [[[NSFileManager defaultManager]URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]lastObject]; 
} 

Guardar texto al final del archivo

si el archivo no existe! Crear y escribir datos

+(void)saveText:(NSString *)textTobeSaved atPath:(NSString*)fileName 
{ 
    NSString *filePath = [NSString stringWithFormat:@"%@.text",fileName]; 

    NSString *path = [[self getDocumentsDirectoryPath].path 
         stringByAppendingPathComponent:filePath]; 
    NSFileHandle *fileHandler = [NSFileHandle fileHandleForWritingAtPath:path]; 
    if(fileHandler == nil) { 
     [[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil]; 
     fileHandler = [NSFileHandle fileHandleForWritingAtPath:path]; 
    } else { 
     textTobeSaved = [NSString stringWithFormat:@"\n-----------------------\n %@",textTobeSaved]; 
     [fileHandler seekToEndOfFile]; 
    } 

    [fileHandler writeData:[textTobeSaved dataUsingEncoding:NSUTF8StringEncoding]]; 
    [fileHandler closeFile]; 
} 

obtener el texto del archivo de con el nombre de archivo especificado

+(NSString *)getTextFromFilePath:(NSString *)fileName 
{ 
    NSString *filePath = [NSString stringWithFormat:@"%@.text",fileName]; 

    NSString *path = [[self getDocumentsDirectoryPath].path 
         stringByAppendingPathComponent:filePath]; 
    NSLog(@"%@",path); 
    if(path!=nil) 
    { 
    NSString *savedString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; 

    return savedString; 
    }else{ 
    return @""; 
    } 
} 

Borrar archivo

+(void)deleteFile:(NSString *)fileName 
{ 
    NSString *filePath = [NSString stringWithFormat:@"%@.text",fileName]; 

    NSString *path = [[self getDocumentsDirectoryPath].path 
         stringByAppendingPathComponent:filePath]; 

    NSFileHandle *fileHandler = [NSFileHandle fileHandleForWritingAtPath:path]; 
    if(fileHandler != nil) { 
     [[NSFileManager defaultManager]removeItemAtPath:path error:nil]; 
    } 

} 
Cuestiones relacionadas