how to write to plist file in objective c [duplicate] - objective-c

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to write to plist successfully?
i m trying to write to test.plist file, which is stored in my supporting files,
here is my code
- (IBAction)acceptAction:(id)sender {
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *pathToFile = [mainBundle pathForResource:#"test" ofType:#"plist"];
NSMutableDictionary *md = [[NSMutableDictionary alloc] initWithContentsOfFile:pathToFile];
[md setValue:#"yes" forKey:#"hasAgree"];
[md writeToFile:pathToFile atomically:YES];
}
- (IBAction)declineAction:(id)sender {
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *pathToFile = [mainBundle pathForResource:#"test" ofType:#"plist"];
NSMutableDictionary *md = [[NSMutableDictionary alloc] initWithContentsOfFile:pathToFile];
NSString *value;
value = [md objectForKey:#"hasAgree"];
NSLog(#"value is %#", value);
}
accept action button for wrtting..
decline action button for reading it out..
but not working at all, any suggestions?

You're not allowed to write in your bundle's directory. You have to use the documents directory instead. Search a little and you'll find enlightenment.

Related

How can I access to the localized strings inside Settings.bundle in Objective-C?

I need to access to the Settings.bundle and get the descriptions and titles with the localized string.
Use NSLocalizedStringFromTableInBundle function. Create an instance of NSBundle with URL of your bundle and use it as bundle argument. Use “Root” as the table name for tbl argument.
For example:
NSBundle *bundle = [[NSBundle alloc] initWithURL: ...];
NSString *string = NSLocalizedStringFromTableInBundle("SOME_KEY", "Root", bundle, "Comment");
In the end I did it this way:
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:#"Settings" ofType:#"bundle"];
NSBundle *settingsBundle = [NSBundle bundleWithPath:resourcePath];
NSURL *url = [settingsBundle URLForResource:#"Root" withExtension:#"plist"];
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfURL:url];
NSArray *preferences = dictionary[#"PreferenceSpecifiers"];
for (NSDictionary *dic in preferences){
NSString *localizedTitle = NSLocalizedStringWithDefaultValue(dic[#"Title"], #"Root", settingsBundle, dic[#"Title"], #"");
}

how to read local json file using objective-c [duplicate]

This question already has answers here:
How do I parse JSON with Objective-C?
(5 answers)
Closed 9 years ago.
I am new to iOS, please help me how can I read a local JSON file using objective-c
SBJSON *parser = [[SBJSON alloc] init];
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"auth_request" ofType:#"json"];
NSError *error = nil;
NSData *JSONData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&error];
NSString *json_string = [[NSString alloc] initWithData:JSONData encoding:NSUTF8StringEncoding];
NSArray *statuses = [parser objectWithString:json_string error:nil];
for (NSDictionary *status in statuses) {
NSLog(#"%# - %#", [status objectForKey:#"loginId"], [status objectForKey:#"secret"]);
}
Just Add
NSArray *tempArray = [json_string JSONVALUE]
in the place of
NSArray *statuses = [parser objectWithString:json_string error:nil];
Don't forget to import

How to save data locally in app? [duplicate]

This question already has answers here:
Working with data in iOS Apps (What to choose? NSData, CoreData, sqlite, PList, NSUserDefaults)
(2 answers)
Closed 9 years ago.
I've been struggling with this for ages now and I really need some good help here. :)
I have an app where I'm parsing a quite big JSON into appdelegate's didFinishLaunchingWithOptions.
My Model Objects are:
Tab:
NSString *title
NSMutableArray *categories
Category:
NSString *title
NSMutableArray *items
Item
NSString *title
NSString *description
UIImage *image
I need to save the data locally, cause the parsing takes about 15 seconds every time my app starts. I'm using the SBJSON framework.
Here's my code for parsing:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"json_template" ofType:#"json"];
NSString *contents = [NSString stringWithContentsOfFile: filePath encoding: NSUTF8StringEncoding error: nil];
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
NSMutableDictionary *json = [jsonParser objectWithString: contents];
tabs = [[NSMutableArray alloc] init];
jsonParser = nil;
for (NSString *tab in json)
{
Tab *tabObj = [[Tab alloc] init];
tabObj.title = tab;
NSDictionary *categoryDict = [[json valueForKey: tabObj.title] objectAtIndex: 0];
for (NSString *key in categoryDict)
{
Category *catObj = [[Category alloc] init];
catObj.name = key;
NSArray *items = [categoryDict objectForKey:key];
for (NSDictionary *dict in items)
{
Item *item = [[Item alloc] init];
item.title = [dict objectForKey: #"title"];
item.desc = [dict objectForKey: #"description"];
item.url = [dict objectForKey: #"url"];
if([dict objectForKey: #"image"] != [NSNull null])
{
NSURL *imgUrl = [NSURL URLWithString: [dict objectForKey: #"image"]];
NSData *imageData = [NSData dataWithContentsOfURL: imgUrl];
item.image = [UIImage imageWithData: imageData];
}
else
{
UIImage *image = [UIImage imageNamed: #"standard.png"];
item.image = image;
}
[catObj.items addObject: item];
}
[tabObj.categories addObject: catObj];
}
[tabs addObject: tabObj];
}
What is the best way of doing this? Using Core Data or NSFileManager?
If you have som code example too it will make me very happy.
This is the last thing i need to fix before the app is ready for app store and it just kills me! I can't solve this problem.
If you are working on iOS then you save a file to the Documents folder. On Mac OS X it would be in the Application Support folder. Since you are on iOS, read this answer for how to access the Documents folder.
All of the objects that you want to store should implement NSCoding. The above variables already do. Should you want to store the tabs, categories and items directly they would need to implement NSCoding. Then all you need is to serialize them to a file. When opening you app you can look for this file and get your objects back without parsing.
The code should look something like this (untested and error checking is ommited for brevity):
- (void) saveStateToDocumentNamed:(NSString*)docName
{
NSError *error;
NSFileManager *fileMan = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [paths[0] stringByAppendingPathComponent:docName];
if ([fileMan fileExistsAtPath:docPath])
[fileMan removeItemAtPath:docPath error:&error];
// Create the dictionary with all the stuff you want to store locally
NSDictionary *state = #{ ... };
// There are many ways to write the state to a file. This is the simplest
// but lacks error checking and recovery options.
[NSKeyedArchiver archiveRootObject:state toFile:docPath];
}
- (NSDictionary*) stateFromDocumentNamed:(NSString*)docName
{
NSError *error;
NSFileManager *fileMan = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [paths[0] stringByAppendingPathComponent:docName];
if ([fileMan fileExistsAtPath:docPath])
return [NSKeyedUnarchiver unarchiveObjectWithFile:docPath];
return nil;
}

How can I read supporting files by line in Xcode?

I'm currently making a web browsing program in Xcode 4.5.1 for OS X and I am trying to work on a list of bookmarks. What I hope to do is to have a supporting file called Bookmarks.txt in which I would list bookmarks like this:
Google
http://www.google.com/
Apple
http://www.apple.com/
Microsoft
http://www.microsoft.com/
I have already looked at a lot of pages discussing this, but none of them apply to what I'm doing. What I have now is
NSMutableArray *list;
NSString *contents;
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Bookmarks" ofType:#"txt"];
if (filePath) {
content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
for (NSString *line in [contents componentsSeparatedByString:#"\n"]) {
[list addObject:line];
}
}
as well as Dave DeLong's method, but I get all kinds of errors with Dave DeLong's and with this one nothing happens. Any help would be great, but I am just starting out at Xcode and know very little.
Thanks!
Your objects aren't initialized.
NSMutableArray *list = [[NSMutableArray alloc] init];
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Bookmarks" ofType:#"txt"];
if (filePath) {
NSString * content = [NSString initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
for (NSString *line in [contents componentsSeparatedByString:#"\n"]) {
[list addObject:line];
}
}

Read .strings file in Objective-C?

I'm creating a Mac app and I want to localize my Labels. I thought a .strings file would be a better choice. But I have trouble reading .strings file in Objective-C. I'm looking for a simpler method.
This is my .string file content:
"LABEL_001" = "Start MyApp";
"LABEL_002" = "Stop MyApp";
"LABEL_003" = "My AppFolder";
...
I have already looked at http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/LoadingResources/Strings/Strings.html.
This is my code:
NSBundle *bundle = [NSBundle mainBundle];
NSString *strFilePath = [[NSBundle mainBundle] pathForResource:#"Labels" ofType:#"strings"];
NSString *tt =NSLocalizedStringFromTableInBundle(#"LABEL_001",strFilePath,bundle, nil);
NSLog(#"STRING ::: %#",tt);
But the string tt gives "LABEL_001", I want "Start MyApp"
What am I doing wrong?
One. You have to name your file Localizable.strings in the <LANGUAGENAME>.lproj directory in the app bundle.
Two. Use the NSLocalizedString macro:
NSString *loc = NSLocalizedString(#"LABEL_001", nil);
Three. If nothing works, you can initialize an NSDictionary using a strings file, as a strings file is a special type of plist:
NSString *fname = [[NSBundle mainBundle] pathForResource:#"whatever" ofType:#"strings"];
NSDictionary *d = [NSDictionary dictionaryWithContentsOfFile:fname];
NSString *loc = [d objectForKey:#"LABEL_001"];
NSString *path = [[NSBundle mainBundle] pathForResource:#"Labels" ofType:#"strings"];
NSData *plistData = [NSData dataWithContentsOfFile:path];
NSString *error; NSPropertyListFormat format;
NSDictionary *dictionary = [NSPropertyListSerialization propertyListFromData:plistData
mutabilityOption:NSPropertyListImmutable
format:&format
errorDescription:&error];
NSString *stringname = [dictionary objectForKey:#"LABEL_001"];
I think it will be helpful to you.
Here the your code
NSBundle *bundle = [NSBundle mainBundle];
NSString *strFilePath = [[NSBundle mainBundle] pathForResource:#"Labels" ofType:#"strings"];
NSString *tt =NSLocalizedStringFromTableInBundle(#"LABEL_001",strFilePath,bundle, nil);
NSLog(#"STRING ::: %#",tt);
The problem here is the 2nd Param "strFilePath", change it to #"Labels" so the above code would become,
NSString *tt =NSLocalizedStringFromTableInBundle(#"LABEL_001",#"Labels",bundle, nil);
For reference, the following line copied from Apple Docs regarding table name,
"When specifying a value for this parameter, include the filename without the .strings extension."
hope this helps.
Simple Code
Just create a method as follows
- (void)localisationStrings
{
NSString* path = [[NSBundle mainBundle] pathForResource:#"localisation" ofType:#"strings"];
NSDictionary *localisationDict = [NSDictionary dictionaryWithContentsOfFile:path];
NSLog(#"\n %#",[localisationDict objectForKey:#"hello"]);
}