Writing and Reading Objects from Resource Files IOS - objective-c

I am in the process of making a level editor for my game. I have used cocos2d to make the game. I have a level node that is a subclass of CCNode and contains all the level objects in the game. The level then gets added to a CCLayer. I want to save all the children of the level (an NSMutableArray) to a file in the resources folder. I want to load this NSMutableArray, loop through it, and add all the saved level objects to the level. I can't save these level objects on the local device because the levels in the final game will be based off of this file and other devices need to have it ready along with all the other game resources. Is there any way to do this or do I have to just save strings containing all the properties of the level objects and search through those strings for the information necessary to load the level? If so, is there a way of reading and writing a c structure to a file in combination with an NSString? Here is what I have so far:
NSString * filePath = #"LevelSaves.txt";
NSString * fileRoot = [[NSBundle mainBundle]pathForResource:filePath ofType:#"txt"];
NSString * fileContents = [NSString stringWithContentsOfFile:fileRoot encoding:NSUTF8StringEncoding error:nil];
NSArray * allLinedStrings = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
ObjectFactory * objFactory = ObjectFactory::sharedObjectFactory();
for (NSString * curString in allLinedStrings) {
NSArray * seperatedString = [curString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#";"]];
NSString * objectID = (NSString*)[seperatedString objectAtIndex:0];
NSArray * properties = (NSArray*)[seperatedString objectAtIndex:1]; //not really sure about this part. Haven't tried saving anything there yet.
objFactory->createObject(objectID,properties);

You cannot save data in the application bundle (which I believe is what you meant by "resources" folder). You can save them in the app's NSDocumentDirectory, and if your objects conform to NSCoding, you can serialize them using NSKeyedArchiver.
Do the above for debug, and when you're done editing the level, bundle it for release and use NSKeyedUnarchiver to deserialize.

Related

Storing an array of CGLayer to file

I'm working on an OSX application where I need to store 446 CGLayers that get placed in a PDF context and am wondering if there's a way to write and read them from a file, rather than generating them when the application loads
I've read that CGLayer is no longer recommended, but I feel they really fit what I need. Also, if I use bitmapGraphicsContexts, they can pixelate when zooming in.
I am able to store them in NSArrays, both by storing them in NSValue and puting them into the array by bridging. I've also tried storing them in C arrays, but that didn't work out.
My problem comes when trying to store these arrays in a file. writeToFile: doesn't work with CGLayers, but NSKeyedArchiver/NSKeyedUnarchiver hasn't worked either, both when the layers are in NSValues or bridged.
Here's my method that attempts to write and read an array containing a single layer from a file.
+(CGLayerRef) colorAnnotations:(CGContextRef)context{
float symbolSize = 8;
CGRect glyphBox = CGRectMake(0,0, 8, 8);
CGLayerRef annotationLayer = CGLayerCreateWithContext (context,glyphBox.size, NULL);
CGContextRef annotaionLayerContext = CGLayerGetContext(annotationLayer);
CGMutablePathRef annot = CGPathCreateMutable();
//Drawing annotation
/*...*/
NSMutableArray *test = [[NSMutableArray alloc]init];
[test addObject:[[NSValue alloc] initWithBytes:&annotationLayer objCType:#encode(CGLayerRef)]];
//Getting file path in Documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/annots.data"];
[NSKeyedArchiver archiveRootObject:test toFile:dataPath];
NSMutableArray *testLoads = [NSKeyedUnarchiver unarchiveObjectWithFile:dataPath];
CGLayerRef layerToReturn;
[[testLoads objectAtIndex:0]getValue:&layerToReturn];
return layerToReturn;
}
I get [NSKeyedArchiver encodeValueOfObjCType:at:]: unknown type encoding ('^')') was raisedfrom this, pretty sure because of the CGLayerRef type.
The lines needed to draw the different annotations I need are pretty long, so I've been trying to figure out a way to have them made and stored in a file without having to make them on startup each time. So far I'm not seeing a way to do this, but was hoping someone here may know of one and would appreciate any help.

Create plist first in Xcode?

I've read conflicting views on this
http://ipgames.wordpress.com/tutorials/writeread-data-to-plist-file/
If I want to use a plist to hold my tile map objects game data, do I have to create a plist with xcode first? and then update that? or do I not need to do that and I can just create it from scratch with code when the game runs?
If I don't have to create one with xcode first, what would be the benefit of doing that?
The code from your link is useful if you want some default data in the property list when the application is started for the first time.
If you don't need default data, don't have to create a property list in Xcode and include it in your application.
NSString *path = ... // path to plist file in Documents directory
NSMutableDictionary *plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
if (plistDict == nil) {
// No plist present (or invalid contents), start with empty dictionary:
plistDict = [[NSMutableDictionary alloc] init];
}
Now you can add/modify/remove items in plistDict and save it later.

Calling multiple XML files

In my application(iPad application) I have 5 folders and inside of each folder i have one XML file. My question is, How can I call all .xml files, in my appDelegate
I have file1.xml, file2.xml, file3.xml, file4.xml,file5.xml (it's a requirement)
for call or adding Path for file1 xml I have this code:
NSString *xml = [[NSBundle mainBundle] pathForResource:#"file1" ofType:#"xml"];
NSData *Data = [NSData dataWithContentsOfFile:xml];
NSXMLParser *Parser = [[NSXMLParser alloc] initWithData:Data];
file1 *parser = [[file1 alloc] initXMLParser];
but how can I have all 5 in my appDelegate class?
and do I need to create specific parser class for each or since all information and tags are the same I just need to add all in my appDelegate
EDIT:
I have to call them from their folder I cann"t change the structure for example
Folder1/file1.xml
Folder2/file2.xml
Folder3/file3.xml and so on
Yes, you need to instantiate an NSXMLParser object for each XML file you're parsing. The simple way to load the XML files is as kimsnarf says: use a for loop and load them in order. If they're in the bundle (which they appear to be), I'd stick them in a specific path under "Resources," like "Resources/SpecialXMLJunk" and just load them by iterating over the results of something like URLsForResourcesWithExtension:subdirectory: (used to get the XML files out of "Resources/SpecialXMLJunk"). So, pseudocode-ish, probably something like this:
NSArray *xmlResourceURLs = [mainBundle
URLsForResourcesWithExtension: #"xml"
subdirectory: xmlResourcesPath];
foreach (NSURL *xmlURL in xmlResourceURLs)
[self loadJunkXMLAtURL: xmlURL];
Create a for-loop and load/parse the files one by one. You should store the parsed data somewhere anyway (in a cache or database) so you don't need to hold on to the files and parsers after parsing. Retrieve data from the cache/database instead.

NSString WriteToFile not stay permanent?

I am trying to save text stored in an NSString variable in a text file that is stored with the main bundle of my project.
So far I have had no success and tried a lot of different methods.
Why doesn't this stay permanent?
NSString *pathToFile = [[NSString alloc]init];
pathToFile = [[NSBundle mainBundle] pathForResource:#"ListOfSavedImages" ofType:#"txt"];
NSLog(#"%#",pathToFile);
NSString *stringToWriteToFile = [[NSString alloc]init];
stringToWriteToFile=#"Adam";
NSLog(#"%#",stringToWriteToFile);
[stringToWriteToFile writeToFile:pathToFile atomically:YES encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"called!");
NSString *contentsOfFile1 = [NSString stringWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"%#",contentsOfFile1);
The actual file doesn't change although the NSLog at the end of this code segment outputs "Adam" but I am also nslogging the contents of the file when the view loads and it always reverts back to the original text(it never actually changes). What am I doing wrong?
I am using Xcode 4.3, ARC, and storyboards.
As you are instantiating your variables locally, they will leak away when you hit the end of the block }.
Try using IVars declared as properties of the particular view controller, synthesized in the .m file.
Look at the C139p at Stanford Course on ITunes, preferably the earlier series given before ARC as this fully explains the concept of data persistence.

File Handling in Objective C

Is there anyway to do Files Handling in Objective-C? I am just trying to do simple read and write and can use 'c' but i am force to use Objective-C classes for that :#. I am looking into NSInputStream, but its going over my head. Is there any tutorial which explains how to use NSInputStream?
I had trouble with basic file i/o when I first hit it in Obj-C as well. I ended up using NSFileHandle to get C style access to my file. Here's a basic example:
// note: myFilename is an NSString containing the full path to the file
// create the file
NSFileManager *fManager = [[NSFileManager alloc] init];
if ([fManager createFileAtPath:myFilename contents:nil attributes:nil] != YES) {
NSLog(#"Failed to create file: %#", myFilename);
}
[fManager release]; fManager = nil;
// open the file for updating
NSFileHandle *myFile = [NSFileHandle fileHandleForUpdatingAtPath:myFilename];
if (myFile == nil) {
NSLog(#"Failed to open file for updating: %#", myFilename);
}
// truncate the file so it is guaranteed to be empty
[myFile truncateFileAtOffset:0];
// note: rawData is an NSData object
// write data to a file
[myFile writeData:rawData];
// close the file handle
[myFile closeFile]; myFile = nil;
If all you need to do is really simple I/O, you can just tell an object to initialize itself from, or write itself to, a filesystem path or URL. This works with several Foundation classes, including NSString, NSData, NSArray, and NSDictionary among others.
Try starting out by looking at the following two NSString methods:
- initWithContentsOfFile:encoding:error:
- writeToFile:atomically:encoding:error:
I find apple's guides short and to the point.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html