Objective C: Write a file programmatically to the

2020-03-31 04:30发布

Possible Duplicate:
Writing into a file objective c

How do I create and write a file to the bundle? I have this:

//make path to file
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,    NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"usnews.txt", [sharedManager.articleNumber intValue] + 1]];
//write file
[textContent writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

but it writes it to the documents folder and is deleted when the app is closed.

2条回答
小情绪 Triste *
2楼-- · 2020-03-31 05:31

You can’t write to the main bundle on iOS. Its contents are cryptographically signed as a part of the App Store submission process; modifying its contents would prevent the application from running.

Documents shouldn’t be deleted when the app is closed. Try passing in an NSError to receive error messages on your write. Also, are you sure that the file is writing to the location you think? You use this for the filename:

[NSString stringWithFormat:@"usnews.txt", [sharedManager.articleNumber intValue] + 1]

But you don’t have a %d format specifier in it, so the number is never inserted into the filename.

查看更多
虎瘦雄心在
3楼-- · 2020-03-31 05:31

Im pretty sure u can. writing into Resources folder is not forbidden.

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"File" ofType:@"txt"];

but as far as i know it is not a good behavior according to Apple Documentation

查看更多
登录 后发表回答