开发者

how can I append to a file in Xcode 4 and where should the file be located?

开发者 https://www.devze.com 2023-03-16 15:39 出处:网络
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 t

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]];
0

精彩评论

暂无评论...
验证码 换一张
取 消