Failure to write NSString to file on iPad

2019-09-02 14:17发布

I'm using a text file to save the changes made by a user on a list (the reason that I'm doing this is so that I can upload the text file to a PC later on, and from there insert it into an Excel spreadsheet). I have 3 data structures: A NSMutableArray of keys, and a NSMutableDictionary who's key values are MSMutableArrays of NSStrings.

I iterate through these data structures and compile a file string that looks much like this:

(Key);(value)\t(value)\t(value):\n(Key);(value).. .so on.

SO, onto the actual question: When I attempt to save it, it fails. I'm 99% sure this is because of the file path that I'm using, but I wanted backup to check this out. Code follows:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *filePath = [paths objectAtIndex:0];
NSString *fileString = [NSString stringWithString:[self toFileString]];
if(![fileString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:NULL]){
    NSLog(@"File save failed");
} else {
    // do stuff
}

(Code above is re-copied, since the actual code is on a different computer. It compiles, so ignore spelling errors?)

I tried using NSError, but I got bogged down in documentation and figured I might as well ask SO while trying to figure out how to properly use NSError (might be a little bit of an idiot, sorry).

99% sure it's the NSArray *paths line that's tripping it up, but I don't know how else to get the documents directory.

Edit: Problem solved, and one final question: If I save it to the App's document directory, where can I go after I close the app to see if it saved properly? If it works like I think it does, isn't it sandboxed in with the app's installation on the simulator? (i.e. no way of checking it)

2条回答
闹够了就滚
2楼-- · 2019-09-02 14:59

NSLog() that filePath string. I think you're trying to write to the directory itself, not to a file.

Try this instead:

filePath = [[paths objectAtIndex:0]stringByAppendingPathComponent:@"myfile.txt"];
查看更多
做自己的国王
3楼-- · 2019-09-02 15:17

What is the file name you want to save? The method

NSArray *paths = NSSearchPathForDirectoriesInDomains(...);
NSString *filePath = [paths objectAtIndex:0];
...
if(![fileString writeToFile:filePath ...

means you are saving the string into a file path which has the same name as a folder. This will of course fail. Please give it a name, e.g.

NSString* fileName = [filePath stringByAppendingPathComponent:@"file.txt"];
if(![fileString writeToFile:fileName ...

and try again.


BTW, to use NSError:

NSError* theError = nil;
if(![fileString writeToFile:fileName ... error:&theError]) {
//                                             ^^^^^^^^^
  NSLog(@"Failed with reason %@", theError);
  // theError is autoreleased.
} 
查看更多
登录 后发表回答