Logging to a file on the iPhone

后端 未结 5 1603
暗喜
暗喜 2020-11-30 20:45

What would be the best way to write log statements to a file or database in an iPhone application?

Ideally, NSLog() output could be redirected to a file using freop

5条回答
  •  再見小時候
    2020-11-30 21:37

    If you want to use Cocoa, NSString and NSData have methods for reading/writing to file and NSFileManager gives you file operations. Here's an example (should work on iPhone):

    NSData *dataToWrite = [[NSString stringWithString:@"String to write"] dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *path = [docsDirectory stringByAppendingPathComponent:@"fileName.txt"];
    
    // Write the file
    [dataToWrite writeToFile:path atomically:YES];
    
    // Read the file
    NSString *stringFromFile = [[NSString alloc] initWithContentsOfFile:path];  
    
    // Check if file exists
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager fileExistsAtPath:path]; // Returns a BOOL    
    
    // Remove the file
    [fileManager removeItemAtPath:path error:NULL];
    
    // Cleanup
    [stringFromFile release];
    [fileManager release];
    

提交回复
热议问题