简体   繁体   中英

NSApplicationSupportDirectory invalid CFStringRef

I'm trying to store a file in the NSApplicationSupportDirectory, since i have a preloaded folder in my app, which i want to add files to once the app have been initialized. I'm trying to NSLog the content of the file, so i can see if it actually worked. From the debugger, i can see that the content is , which i don't not what means. Anybody?

NSString *document = [NSString stringWithFormat:@"%@ %@ %@ %@ %@", description, focus, level, equipment, waterDepth];

//NSLog(@"%@", document);

//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *supportDirectory = [paths objectAtIndex:0];

//filename
NSString *filename = [NSString stringWithFormat:@"%@/%@", supportDirectory,[_nameTextField.text stringByAppendingString:@".txt"]];
NSLog(@"%@", supportDirectory);
NSLog(@"%@", filename);

[document writeToFile:filename atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];

NSString *content = [[NSString alloc]initWithContentsOfFile:filename usedEncoding:nil error:nil];
NSLog(@"%@", content);

You're not passing a string encoding, you are passing NSStringEncodingConversionAllowLossy which is an option that can affect how encoding conversion happens for certain methods (not the one you're using). You need to pass something like NSUTF8StringEncoding .

When you write or read files, it is highly recommended to use the error parameter and handle the cases where you get an error. Also, this is very useful to help you debug your code.

For example, in your case, you can do like this:

NSError *error = nil;
BOOL success = [document writeToFile:filename atomically:NO encoding:NSStringEncodingConversionAllowLossy error:&error];

if (!success) {
    NSLog(@"Could not write file: %@", error);
} else {
    NSString *content = [[NSString alloc]initWithContentsOfFile:filename usedEncoding:nil error:&error];
    if (!content) {
        NSLog(@"Could not read file: %@", error);
    }
}

If you get an error that says that The operation couldn't be completed. No such file or directory The operation couldn't be completed. No such file or directory , that means that you did not previously create the folder. So you create it before trying to add content to it:

NSString *supportDirectory = [paths objectAtIndex:0];
NSError *error = nil;
BOOL success;
if (![[NSFileManager defaultManager] fileExistsAtPath: supportDirectory]) {
    success = [[NSFileManager defaultManager] createDirectoryAtPath:supportDirectory withIntermediateDirectories:YES attributes:nil error:&error];
    if (!success) {
        NSLog(@"Could not create directory: %@", error);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM