Saving data to file

_Event_Horizon
Unregistered
 
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])
{
NSBeep();
}
}

}


Thanks..
Quote this message in a reply
Sage
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:

Code:
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
_Event_Horizon
Unregistered
 
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 2,644 Sep 30, 2010 12:35 PM
Last Post: konrad77
  Saving High Scores Nick 7 4,180 Jun 20, 2005 12:08 AM
Last Post: Malarkey
  Saving/Loading... CarbonX 6 4,003 Sep 25, 2004 07:47 AM
Last Post: Steven