Saving data to file

Post: #1
I'm just learning Cocoa
Have a problem getting some basic information to a file.
MyGameModel contains a Grid, boolean values for game, score and so on..
So as a "Save file" i would like all the information of the gamemodel to be saved.

I'm using the code below but nothing happens.

- (void)didEndSaveSheet:(NSSavePanel *)savePanel returnCode:(int)returnCode contextInfo:(void *)contextInfo {
[savePanel orderOut:nil];
if (returnCode == NSOKButton) {
NSString *filename = [savePanel filename];

NSData *data;

//Accordingly to debugger data gets copyed
data = (MyGameModel*)_myGameModel);

// No file created at all
if (![data writeToFile:filename atomically:YES])


Quote this message in a reply
Posts: 1,199
Joined: 2004.10
Post: #2
What you're doing is casting your data into an NSData, which isn't going to work. NSData's a container for data..

You need to do something like:

data = [NSData dataWithBytes:(const void *)myGameModel length:sizeof( MyGameModel )];

Except, that won't actually work unless your game model is *entirely* stack allocated. If you have an malloced or new'ed arrays that won't work.

If your game model is ObjC, you might look into the NSCoding protocol.
Quote this message in a reply
Post: #3
I'm coding in objc

Its writing something.. Smile
but when i read it back into the game it comes out as junk..

if (result == NSOKButton) {
NSString *fileToOpen = [oPanel filename];

//Obtain data
NSData *mydata = [NSData dataWithContentsOfFile:fileToOpen];

//read it back into the model
_myGameModel = [NSData dataWithBytes:(const void *)mydata length:sizeof( MyGameModel )];


So i'll look in to NSCoder / NSDecoder or i was thinking of directly pulling the values from the class and storing them one by one as strings, maybe easier..

Anyway Thanks,
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Game Editor, Saving levels help needed konrad77 3 3,015 Sep 30, 2010 12:35 PM
Last Post: konrad77
  Saving High Scores Nick 7 4,685 Jun 20, 2005 12:08 AM
Last Post: Malarkey
  Saving/Loading... CarbonX 6 4,270 Sep 25, 2004 07:47 AM
Last Post: Steven