开发者

How to load a txt file into an array

I coded a method to load a txt file into an array. However, I'm not really happy with it as it looks terribly cumbersome to my beginner's eyes (I'm sure I don't need 50% of my code) and I am somehow wondering how I can specify the exact format of my txt file, e.g. NSUTF8StringEncoding.

Here is my code:

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMa开发者_如何学Csk, YES); 
 NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory

 NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Sample.txt"]; 

if (filePath) { // check if file exists - if so load it:
    NSString *myText = [NSString stringWithContentsOfFile:filePath];
    if (myText) {textView.text=myText;}
}

For any suggestions of how to polish this up and specify the right format, I'd be very grateful.


Try the following, assuming your file is in your bundle:

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

NSError * error = nil;

NSString * contentsOfFile = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];


Into an array? You mean into a string, since is exactly what you're doing...

However, your code looks not bad, and most of it is just to grab the documents directory path, and that's not your fault, since it's exactly done this way, according to many knowledge bases.

As of the encoding, stringWithContentsOfFile is deprecated, please use stringWithContentsOfFile:encoding:error: (see the docs) and you will be able to specify the correct encoding and get accurate error descriptions.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜