Problem with reading data from plist in the iPhone SDK - iphone

I'm creating a myDb.plist file in my resources folder and trying to read it, but it's not getting read. I'm using the following code.
NSString* plistPath = [[NSBundle mainBundle] pathForResource:#"myDb" ofType:#"plist"];
contentArray = [NSArray arrayWithContentsOfFile:plistPath];
contentArray is showing null.
What can I try to resolve this?

Make your plist data array and not dictionary. Dictionary also works but i tried with hit and trial. Also, print NSLog your data, if in case you need, to check the input from plist.

Related

write into plist file using NSDictionary object

Sorry I saw similar questions but they don't seem to have some full answers for me. And i try to put it in order so that people will not hate me or my poor english.
I am working with Xcode 4.2 with storyboard and ARC
I can read from my plist file. My task is simply to write back the updated value(s) to my plist file.
My plist is contain in "supporting files" sub folder of the main folder (where story-board is things goes). the file is call Global.plist and GlobalValue2 is a element of the file type string.
So the read file part looks like this
NSString *plistfile = [[NSBundle mainBundle] pathForResource:#"Global" ofType:#"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:plistfile];
FirstValueTextBox.text = [[dict valueForKey:#"GlobalValue1"] stringValue];
learn it from some handy youtube video works just fine. updates the value to my text box.
The real problem comes in when I write back my plist file. When i try the following
NSString *plistfile = [[NSBundle mainBundle] pathForResource:#"Global" ofType:#"plist"];
NSMutableDictionary *dict = [NSMutableDictionary
dictionaryWithContentsOfFile:plistfile];
[dict setValue:#"ABC" forKey:#"GlobalValue2"];
SecondValueTextBox.text = [dict valueForKey:#"GlobalValue2"];
[dict writeToFile:plistfile atomically:YES];
the result is I really saw a updated value pop up on the second text box, but the plist file remain unchanged.
The following are the break down of my questions and my guess for the problem
I try to use NSDictionary(not NSMutableDictionary) and call setValue (crash in runtime)
my guess: NSDictionary object itself is readonly so it crash me when i say add value. But why don't it error me when in coding time? if the object is readonly
I use NSMutableDictionary can call setValue. it doesn't crash me and when i call the updated value at "SecondValueTextBox.text = [dict valueForKey:#"GlobalValue2"];" it really return me the updated value. but the content inside of the plist file is not changed. Which is the result I have right now.
my guess: after some search here and there I think "supporting files" is read only too. pure guess did see anyone directly talk about it.
I did try to move on a little more and some people talks about a "document folder" in Xcode that is a read and write place. I think people also talk about write a code to access that folder. Can someone show me the code here.
My last question, can I hook up my Xcode to that "document folder" or where can i see it(the real file folder structure is different from inside Xcode I think). So that i can see and edit my plist file for testing, and i can see the real result without using codes and stuff
I will be much appreciated if people can tell me my guess is right or wrong and the answer to my 3 and 4 question.
In order for your changes to be persisted in your plist, you would indeed need ot copy it from the resource bundle to the documents dirtectory on launch of the application, then use the plist in the documents to read and write.
Here is how you can copy the file:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:#"Global.plist"];
if ([fileManager fileExistsAtPath:plistPath] == NO) {
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:#"Global" ofType:#"plist"];
[fileManager copyItemAtPath:resourcePath toPath:plistPath error:&error];
}

Basics Introduction To Using CHCSVParser

I'm implementing CHCSVParser into my iPhone app (thanks Dave!) however I'm really confused on how to use it. I've read the read-me and searched some questions on SO but still not 100% sure what to do.
I have a .CSV file with maybe 5000 rows of data and 3-4 columns.
I want this data to in return, load my UITableView along with its corresponding detailViewController.
So I'm assuming I need to somehow implement the API's array method but can anyone help get me started?
I'm glad you like it :)
Basically, CHCSVParser only parses CSV files. You give it a path to a CSV file, and it'll give you back a whole bunch of NSStrings. What you do beyond that point is entirely up to you.
So let's say you've included a CSV file in your iOS app called "Data.csv". Here's how you'd use CHCSVParser to parse it:
NSString *path = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"csv"];
NSError *error = nil;
NSArray *rows = [NSArray arrayWithContentsOfCSVFile:path encoding:NSUTF8StringEncoding error:&error];
if (rows == nil) {
//something went wrong; log the error and exit
NSLog(#"error parsing file: %#", error);
return;
}
At this point, rows is an array. Each element in rows is itself an array representing a single row in the CSV file. And each element of that array is an NSString.
So let's say your CSV file looks like this:
Barringer,Arizona,United States,Earth
"Chicxulub, Extinction Event Crater",,Mexico,Earth
Tycho,,,Moon
Lonar,Maharashtra,India,Earth
If you run it through the parser, you'll get back the equivalent of this:
[NSArray arrayWithObjects:
[NSArray arrayWithObjects:#"Barringer",#"Arizona",#"United States",#"Earth",nil],
[NSArray arrayWithObjects:#"Chicxulub, Extinction Event Crater",#"",#"Mexico",#"Earth",nil],
[NSArray arrayWithObjects:#"Tycho",#"",#"",#"Moon",nil],
[NSArray arrayWithObjects:#"Lonar",#"Maharashtra",#"India",#"Earth",nil],
nil];
What you do with it then is your business. The CSV parser doesn't know anything about UITableView, so you get to take this data and re-structure it in a way that you're comfortable dealing with and that fits in to your data model.
Also, remember that by using CHCSVParser, you agree to abide the terms under which it is made available. :)

NSBundle returns nil

I wanted to read version information of my application from the plit file.
For this I am using a code as shown below.
NSString *myFilePath = [[NSBundle mainBundle]
pathForResource:#"MyApp-Info"
ofType:#"plist"];
// Format output
NSLog(#"%#",myFilePath);
The output
2010-08-31 17:14:10.095 MyApp[8759:20b] (null)
It always returns nil even if I tried to Import an existing file of type, text.txt still return nil, where text.txt is imported in the application.
I have goggled for the problem dont every one recommends to use NSBundel to read an pre imported file, but no use.
Any help, or an better way to read application version.
Got the solution via another link in the stack overflow here.
NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleVersion"];
NSLog(#"%#",version);
The reason this doesn't work is because pathForResource looks for stuff inside "MyApp.app/Contents/Resources". The Info.plist file does not reside inside the resources folder, so it's going to return nil if you look for it there. The correct way to get at it is to use the "infoDictionary" method on NSBundle.

read single line from text file in objective-C

i'm new to iPhone programming and coding in XCode SDK.I want to access and read the configuration file which i have placed in Resource folder in XCode,my configuration file looks like this
#key=value$
#vinu=flower$
#cathy=fruit$
I want to compare the key and access the value from configuration file.
Since i'm working with iPhone OS, i cant use NSWorkspace.Hence i'm using NSFileHandle.
This is how my code looks like,
NSString *path = [[NSBundle mainBundle] pathForResource:#"configuration" ofType:#"txt"];
NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:path];
NSString *txtString = [[NSString alloc] initWithData:
[readHandle readDataToEndOfFile] encoding:NSUTF8StringEncoding];
please let me know is the procedure correct, and how to proceed. ??
Thank You.
Do yourself a favor and save it as a plist, and not a straight text file.
However, if you need to read it in like that, the simplest way is to read it into a string and then go from there, ie:
NSString * fileContents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
If the file is super large and the only reasonable way to read it is line-by-line, then you can quickly see that this is something that has come up before (Particularly: Objective-C: Reading a file line by line).

Loading data files in iPhone project

How does one read a data file in an iPhone project? For example, lets say I have a static file called "level.dat" that is structured as follows:
obstacles: 10
time: 100
obstacle1: 10,20
...
I would like to read the contents of the file into a NSString then do the parsing. How do I read the contents of a file into a string? Also, where in the project should the "level.dat" file reside? Should it be under "Resources" or just in the main directory?
Thanks in advance!
See this answer: How to fopen() on the iPhone? which shows how to get access to resources in your bundle. Once you have the path, just use [NSString stringWithContentsOfFile:encoding:error:].
NSString *path = [[NSBundle mainBundle] pathForResource: #"level" ofType: #"dat"]
NSError *error = nil;
NSString *data = [NSString stringWithContentsOfFile: path
encoding: NSUTF8StringEncoding
error: &error];
While this isn't what you asked for, consider turning your files into plists. You will have to reformat them into XML, but then you can load them straight into a NSDictionary with:
dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"levels" ofType:#"plist"]];
Have you considered putting the data in an SQLite database instead of a flat file? I find that the API is very easy to use on the iPhone.
It is how I do all of my data storage on the phone now.
If you need help parsing the data string, there's a helpful article on Cocoa For Scientist