views:

140

answers:

2

Hi there!

I implemented saving and loading methods in my document-based application. In the saving method, I have

[NSArchiver archivedDataWithRootObject:[self string]];

Where [self string] is a NSString. When saving a file with just "normal content" inside of it, the contents of the file created are:

streamtypedè@NSStringNSObject+normal content

Is there a way to store in a file just raw text?

Thanks for your help, and merry christmas!

—Albé

+7  A: 

There are methods inside NSString for saving in a file:

NSString * s = @"Foo bar";

NSError * err = NULL;
BOOL result = [s writeToFile:@"/tmp/test.txt" atomically:YES encoding:NSASCIIStringEncoding  error:&err];
diciu
In other words, don't use NSArchiver.
Dewayne Christensen
Thank you, very much. :-)
Alberto
Well. How I can use that method? `- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError` returns data. Where I should put the NSString method?
Alberto
writeToFile:atomically:encoding:error is a method on NSString. See the documentation.
bbum
Instead, I used `[string dataUsingEncoding:NSUTF8StringEncoding];`. It works as expected.
Alberto
By the way: NSString is a beast. I first shook my head when I saw stringWithContentsOfURL.
stesch
A: 

Since i am new with cocoa, i don't know if this is the right way to do it or even a valid way.

But after a quick look at the documentation i found this method of NSString instances, - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding

A quick try on a sample project it worked fine with: - (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError

So something like this might work for you:

- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError {
    return [[self string] dataUsingEncoding:NSUnicodeStringEncoding];
}
apod