开发者

string is not being written in file - iPhone

I am using the following code in iPhone to write a string into the file that is stored in my iPhone Project Resource Folder. When i try to read its reading the data successfully but when i try to write its not writing the file although its aloso not giving me an开发者_C百科y error.

this is my code:

NSString *myString; //Assuume the string you want to write is this
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"myfile.txt"];
[myString writeToFile:path atomically:YES];

Please can anybody guide.


- (void) testStringReadWrite {
    NSString *myString = @"abcd efgh"; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"myfile.txt"];
    CFShow(path);
    NSError *error = nil;

    [myString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
    if (error) {
        NSLog(@"%@",error);
    }


    NSString *readString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
    if (error) {
        NSLog(@"%@", error);
    } else {
        CFShow(readString);
    }

}


The writeToFile:atomically: has been depredecated in iOS 2.0. Use writeToFile:atomically:encoding:error: instead. You should check the content of the string, for example by NSLog() function. Inappropriate initialization can cause a failure.

NSLog(@"%@", myString);
[myString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];


Just my two cents, coming from OS X, I am used to calling writeToURL() instead of writeToFile(). Turns out, writeToFile() is the one that worked for iOS.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜