Search code examples
objective-ccnsfilemanager

createFileAtPath:contents:attributes storing a NSString


The createFileAtPath:contents:attributes for Objective-C: contents requires an NSData type, but I want to create a file with a NSString content. How do I do this?

I know it's probably a really basic answer, but I'm just starting to learn how to use Objective-C, and it has so many different data types and objects compared to other languages I've used.

Thanks!


Solution

  • You can try creating NSData with the content of the string, like this:

    NSString *s = @"Hello, world!";
    NSData *d = [s dataUsingEncoding:NSUTF8StringEncoding];
    

    You can also store an NSStrng to a file directly:

    [s writeToFile:@"/my/file/path/file.txt" atomically:NO encoding:NSUTF8StringEncoding error:nil];
    

    NOTE This answer is edited after Ken Thomases's note.