J'ai trouvé cet extrait en ligne à écrire, puis ajouter des données à un fichier texte:onglet fichier délimité dans c objectif
- (void)appendText:(NSString *)text toFile:(NSString *)filePath {
// NSFileHandle won't create the file for us, so we need to check to make sure it exists
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:filePath]) {
// the file doesn't exist yet, so we can just write out the text using the
// NSString convenience method
NSError *error = noErr;
BOOL success = [text writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!success) {
// handle the error
NSLog(@"%@", error);
}
}
else {
// the file already exists, so we should append the text to the end
// get a handle to the file
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
// move to the end of the file
[fileHandle seekToEndOfFile];
// convert the string to an NSData object
NSData *textData = [text dataUsingEncoding:NSUTF8StringEncoding];
// write the data to the end of the file
[fileHandle writeData:textData];
// clean up
[fileHandle closeFile];
}
}
Cela me semble logique. J'ai une classe qui a 3 propriétés, de NSString, NSInteger et NSString. Lorsque j'essaie d'utiliser cette méthode, je le fais:
for (MyObject *ref in array) {
NSString *stringToFile = [NSString stringWithFormat:@"%@\t%i\t%@", ref.ChrID, ref.Position, ref.Sequence];
[self appendText:stringToFile toFile:filePath];
}
Cela ne semble pas tout à fait correct. Mes données ressemblent à ceci:
NSString *tab* NSInteger *single space* NSStringNSString *tab* NSInteger newline
NSStringNSString *tab* NSInteger newline
NSStringNSString *tab* NSInteger newline
NSStringNSString *tab* NSInteger newline
NSStringNSString *tab* NSInteger newline
NSStringNSString *tab* NSInteger newline
NSStringNSString *tab* NSInteger newline
NSStringNSString *tab* NSInteger newline
...
Je ne suis pas sûr de ce qui se passe pour le faire ressembler à ceci. Quand je NSLog les données, il semble bien. Mais quelque chose avec la première ligne se gâte, et tout semble être éteint. Des pensées? Merci.
D'abord, mettez une nouvelle ligne (\ n) à la fin de la chaîne de format. Vous pourriez avoir besoin d'une paire \ r \ n. – Flyingdiver
En outre, quelle est la déclaration pour MyObject? – Flyingdiver
@Flyingdiver Pour autant que je sache, les paires '\ r \ n' sont nécessaires sur Windows, mais pas sur les systèmes de fichiers basés sur Unix (y compris OS X et iOS), même si la plupart des systèmes Unix en sont tolérants. – jlehr