I'm working with Xcode 4 and I'd like my iphone 4 applicati开发者_运维问答on to append a line to a file every time I run a test. Is there any fast way to do this? If so, where exactly am I allowed to write inside the iphone directory hierarchy?
Thanks.
You can't write inside the bundle of the iPhone application because that would break encryption. You can write in the Documents
directory, or somewhere under <apphome>/Library
.
Since Documents
may become visible for the iTunes user if you add UIFileSharingEnabled
to your Info.plist
, and this is a file private to the application, adding the file under Library
is better. Not that it matters much during testing. Apple documents related to this: Technical Q&A QA1699: Storing Private Data, A Few Important Application Directories.
You can use this code in an iPhone application to append text to a file:
// get path to Documents/somefile.txt
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"somefile.txt"];
// create if needed
if (![[NSFileManager defaultManager] fileExistsAtPath:path]){
[[NSData data] writeToFile:path atomically:YES];
}
// append
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:path];
[handle truncateFileAtOffset:[handle seekToEndOfFile]];
[handle writeData:[@"line of text\n" dataUsingEncoding:NSUTF8StringEncoding]];
精彩评论