views:

3766

answers:

3

I need to store certain information while my application is executing and again fetch it at the time the application starts. I tried storing it in XML using GData but didn't succeed. I used the NSFileHandle it doesn't give me an error but it fails to create a .txt file for read / write purpose. Is there any other way of storing and retrieving the data on the iPhone. Below is my code for NSFileHandle.

NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"myFile.txt"];
//NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:@"file://localhost/Users/shraddha/Desktop/info.txt"];
NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:@"myFile.txt"];
[fh seekToEndOfFile];
NSData *data = [camName dataUsingEncoding:NSASCIIStringEncoding];
[fh writeData:data];
[fh closeFile];

For Reading

NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"myFile.txt"];
//NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:@"file://localhost/Users/shraddha/Desktop/info.txt"];
NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:@"myFile.txt"];
if(fh == nil)
 return nil;
else
{
 NSData *data = [fh readDataOfLength:8];
 NSString *retStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
 return retStr;
}
+3  A: 

You can use a sqlite database to store persistent data on the iPhone. Here is a blog post that should get you pointed in the right direction:

http://dblog.com.au/iphone-development-tutorials/iphone-sdk-tutorial-reading-data-from-a-sqlite-database/

bcwood
+3  A: 

Every iPhone application has at its disposal the ability to read/write name/value pairs which can be very, very useful for storing small information like user preferences. These preferences can also be edited by the user of your application (if you choose).

Another option you have which is more robust than trying to do text file storage and retrieval (I never liked this option, especially with the crappy XML parsing support on the iPhone) is sqlite. sqlite is a really light-weight relational database engine that is included with every iPhone and iPod touch.

Kevin Hoffman
+8  A: 

You're trying to write to the resource directory which you probably don't have permission to do. Try changing the first line of your code to point to the document directory:

NSArray *savePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSMutableString *savePath = [NSMutableString stringWithString:[savePaths objectAtIndex:0]];
[savePath appendString:@"/myFile.txt"];

Also, you don't need to worry about file handles. NSData is capable of writing itself to disk:

BOOL result = [data writeToFile:savePath atomically:YES];
Stephen Darlington