Open .string files as an NSDictionary - objective-c

How do I open a .string file as an NSDictionary?
Edit: I want to be able to use it like this:
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:#"dict.plist"];
NSDictionary *strings = [[NSDictionary alloc] initWithContentsOfFile:#"Strings.strings"];

If you really want it in a dictionary, you can load it using [NSDictionary dictionaryWithContentsOfFile:], since it is in “Old-style ASCII” format. I have used this technique before on Mac OS X, but I'm not sure you can do the same for iOS.
However, if you want a translation for a particular string, there are at least two ways to do it:
NSLocalizedStringFromTable() will allow you to load strings from files other than the normal Localizable.strings file. Provide the name of your strings file (without the extension).
NSBundle's localizedStringForKey:value:table: method. This essentially performs the same operations as the method above, and as above, provide the name of your strings file without the extension.

.string files just store key/value pairs, like:
"StringKey" = "some localized text";
you can get the text for a specific key using NSLocalizedString. If you want to get all the strings in a file, I suppose you could read the Localizable.strings file and parse it.

Related

How to take parameters from plist?

I am quite new at Objective-C programming, I was asked to develop a framework that could be implemented in IOS apps. This framework has three methods (that take a model object as an argument) that perform API comsumption and return a message (that takes from response). The problem is that I was asked to store the module parameters in plist, and I don´t have a good clue what this means. I been reading about plist and I know they can store serialized objects. But I really don´t understand what it means to be storing all parameters on this file.
A plist is essentially a dictionary (or NSDictionary) -- with keys and values -- written to a specific file format that iOS expects.
To write a plist file is easy when you do it from Xcode. In Xcode 10.3 you can go to "File" -> "New" --> "File..." and select "Property List" from the types of files you see:
I created a file (as an example) named "SomeFile.plist" and then added a couple keys & values to it:
Now after you get this file included in your new project, you need to read the keys & values back in. Here is a related question that shows you different ways to read the plist / dictionary, such as:
NSString *path = [[NSBundle mainBundle] pathForResource: #"YourPLIST" ofType: #"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile: path];
NSString *name = [dict stringForKey: #"RaphaelName"];

how to write NSDate in text file

I'm using [str writeToFile:path atomically encoding error]
to write in file. It works successfully for NSString but doesn't work for NSDate/NSData.
Please tell me how to write in file.
Simple, cheater solution: put it inside a structure that does support writing to a file.
NSDate* variable = ...;
[#[ variable ] writeToFile:path atomically:YES];
That's to say, put it inside an array or dictionary.
If you want to output it to a text file (as you title suggests but you don't mention in the question), you need to convert the date into a string first. Use NSDateFormatter.
Without knowing what's inside your NSData it's not really possible to say how to output to a text file. Maybe convert to base 64 first?

Objective-C - Json for Game or is there a better way

i have some questions about json! i hope anybody can help me!
I have created a game and now i want to bring some variables out of my Game into a json file!
So i want to ask, is it possible to bring floats and an array
NSArray *points = [NSArray arrayWithObjects:
[NSValue valueWithCGPoint:CGPointMake(50.0, 150.0)],
[NSValue valueWithCGPoint:CGPointMake(350.0, 300.0)],nil];
into a json file?!
Also i want to bring my background-images for the different levels in the json file.
Is it possible to do it with json or anybody know a better way.
It would be great if anybody could tell me. Or anybody know a good tutorial?!
Thanks
If you don't have to serialise the objects to move between environments, then I wouldn't bother with JSON... if you are consuming a web service or something, then they are great... if you have them in values, then I would just store them in a plist assuming you have no interchange.
To answer the question about the background images ... you would simply store the filename/path to the image. That way, multiple files or levels could potentially refer to the same asset.
JSON supports hashes (dictionaries) and arrays as containers, which can contain hashes, arrays, numbers, strings and booleans within them. So to capture that data you might have a structure like this:
{
"points":[
[50.0, 150.0],
[350.0, 300.0]
]
}
And read it back with something like this:
NSArray *pointsData = [json objectForKey:#"points"];
NSArray *points = [NSArray arrayWithObjects:
[NSValue valueWithCGPoint:CGPointMake(
[[pointsData objectAtIndex:0] objectAtIndex:0],
[[pointsData objectAtIndex:0] objectAtIndex:1]
)],
[NSValue valueWithCGPoint:CGPointMake(
[[pointsData objectAtIndex:1] objectAtIndex:0],
[[pointsData objectAtIndex:1] objectAtIndex:1]
)],
nil];
Cocoa supports only these type in its JSON support.
NSNumber (integer, float, boolean)
NSString
NSArray
NSDictionary
Whatever you want to save/load, you should organize your data to use only those types. Direct use of NSValue is not supported, so you need to make something like this.
NSDictionary* point = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:444f],
#"x",
[NSNumber numberWithFloat:555f],
#"y",
nil];
And save the dictionary.
In addition, you also can use equivalent new literal syntax which is mainly designed for Property List.
NSDictionary* point = #{ #"x" : #444f, #"y": #555f };
This is equal to above example.
CAVEAT: All keys of NSDictionary must be NSString when you are saving the data to JSON or Property List.
Consider using of Property List
If you are targeting only iOS, Property List is always right and better choice to save/load some small amount of variables. Also Xcode will give you better editor.
Support for JSON in Cocoa is just a subset of the Property List, and mostly similar. So look at the Property List first, and than you will be able to use PLIST or JSON easily. (this is why there's no guidance document for JSON in Cocoa)
Background Images
It is possible to save image data in JSON or Property List, but it is usually not recommended. Because JSON or PLIST need to load at once. This means all file content must be loaded into memory. If you put multiple images in a JSON or PLIST file, it will get bigger up to multiple megabytes easily. And iOS devices doesn't have much memory, so your program may crash.
So it is recommended to store only path to image file in JSON or PLIST file - as like #JoelMartinez indicates -, and load the each image file directly from the path.

NSMutableArray Meta-Data when exported to CSV file

Looking for some advice with an iOS application.
Essentially what my app does is generate a CSV file that logs certain events within a period of time. So users can press a button and an entry will be added to the log saying "Event of type X happened at Time T"
The way I'm doing this is by maintaining an NSMutableArray which stores NSStrings. Each event adds a string to the NSMutableArray.
When the user is done with a session, they can "export" the file. I'm using the NSMutableArray's writeToFile; then I use an e-mail interface to send that file as a CSV to a target e-mail.
It all works, except the CSV file that is generated has some meta-data in it. Specifically, I believe at the top of the file I see and at the beginning of each row of cells when opened in excel.
Is this something inherent in the data structure (NSMutableArray) or data type (NSString) that I am using? Is there a way for me to just get the raw data?
I can upload code if need be (I'm not near the work computer now though, so I'm testing the waters to see if there is something simple I can do to stop seeing this meta-data).
Thank you!
CSV is a very simple format. You can separate the strings with semi-colons and then write everything to a file using NSOutputStream.
This code assumes you already have a string array with CSV rows:
NSOutputStream* csvoutput = [NSOutputStream outputStreamToFileAtPath:filepath append:NO];
[csvoutput open];
for (NSString* str in array) {
NSString* tempStr = [str stringByAppendingString:#"\n"]; //new line
NSData *strData = [tempStr dataUsingEncoding:NSUTF8StringEncoding];
[csvoutput write:(uint8_t *)[strData bytes] maxLength:[strData length]];
}
[csvoutput close];
You better create a model class (Event) and fill the array with Event-instances instead of strings. Thats cleaner and more efficient. Then you would create the CSV-strings when exporting to a file.

I need help parsing a .csv file based on if a string contains a given substring and saving that string to a new file in Objective C

Basically, I am searching through a list of foods. The fields I am using in the .csv file are: the name of the food, the type of the food represented by a number (type of food would be meat, vegetable, fruit, etc). I want to go through the .csv file line by line, and if the type of food is say a fruit (represented by the number 1), then I want to save that entire line in a new file. I want to go through the ENTIRE list of foods and save each to the new file. How could I go about doing this in objective c? My idea was to search the string for a substring (in this case, the number 1) and if it contains the substring, then I want to save the entire line in a new file, called fruit. I understand this in theory, but am having trouble understanding how to parse a .csv file in this way.
NJones is right - CSV files suck and you don't see them often in Objective-C, so try to avoid them.
However, you can load a CSV file with the following code:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"food" ofType:#"csv"];
NSString *fileContents = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
If you have the contents of a CSV stored in memory, either from a file on disk or from a web service, you can turn it into an array of line records:
NSArray *lines = [fileContents componentsSeparatedByString:#"\n"];
The first line in a CSV file is typically you're header, but after removing it (or ignoring it), it's simply a matter of enumerating over the remaining lines.
for (NSString *record in lines) {
NSArray *values = [record componentsSeparatedByString:#","];
//values is now an array of the contents of the CSV file. Do stuff with it.
}
This code assumes a lot about the CSV file structure, such as the fact that there are no commas in your food names, etc. In general, avoid CSV files whenever possible. Take a look into persisting data on disk as JSON or, better yet, as a Core Data store.
-(BOOL)readFromURL:(NSURL *)absoluteURL ofType:(NSString )typeName error:(NSError *)outError
{
NSString *fileString = [NSString stringWithContentsOfURL:absoluteURL
encoding:NSUTF8StringEncoding error:outError];
NSLog(#"------- file string ----- %#",fileString);
if ( nil == fileString )
return NO;
NSArray* allLinedStrings =
[fileString componentsSeparatedByCharactersInSet:
[NSCharacterSet newlineCharacterSet]];
NSLog(#"------- file string ----- %#",allLinedStrings);
// write your code how you want display
}
If your csv file is fairly simple with a well defined format, you may have the best luck with your own code based upon the suggestion from #Ash Furrow.
If you are facing a more complicated import, you may find the tutorial and CSV parsing class created by Matt Gallagher to be very helpful. He did a really nice job creating a nice way to deal with CSV files. You can check it out here: http://cocoawithlove.com/2009/11/writing-parser-using-nsscanner-csv.htmlhttp://cocoawithlove.com/2009/11/writing-parser-using-nsscanner-csv.html