Aaron to Wall: Frack You
These are the moments that keep you going, that sustain you through the impossible times. Just now, I’ve solved the stupid saving problem. And my God, it’s simple simple simple.You need to use one of three methods to enact a Save motion; the most common appears to be dataOfType:error:. That’s the one that I used, and indeed that’s appropriate for this situation. I’ve got a wired-up Save command, and the contents of an instance variable that I want to stuff into a file. But when I was reading back the file, I was getting nothing.
I thought my problem was that nothing was being saved. But it turns out that things were saving fine! All you have to do is convert your data into an NSData object. In my case, it’s a one-liner:
NSData *data = [[textView string] dataUsingEncoding:NSUTF8StringEncoding];
That gets passed back to the mysterious Cocoa machinery, which writes it out to the file on your disk.
On the reading side, you have to enable one of three methods; again, the most common is readFromData:ofType:error:, and it proved to be the right one, eventually.
That is the method that wasn’t working. And the reason was staring me in the face the whole time. Observe: you need to convert the received file’s NSData into the format you want to use, in my case, an NSString. Again, that’s a one-liner:
file = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
But then you’ve got to tell your interface elements to display that shit. And here’s where things fly off the rails. See, at the time in the game where Cocoa is reading your data, it doesn’t have a working interface to put your value! So when I’m doing something like this in my readFromData:ofType:error: method:
if (file) { readSuccess = YES; [textView insertText:file]; }
Well, textView doesn’t actually exist. The compiler doesn’t tell me shit, by the way. But if you read closely page 160 of Hillegass (3rd Ed.), the answer is right there.
What to do? Override windowControllerDidLoadNib:, and tell it to load the freshly-created data object into the interface:
– (void)windowControllerDidLoadNib:(NSWindowController *) aController { [super windowControllerDidLoadNib:aController]; if(file) { [textView insertText:file]; } }
I feel like I just fell off the turnip truck! Yesterday! With copious fluid behind my ears!
But on the plus side, I can open and save documents now. That’s a good thing.