Add key to NSDictionary (iPhone SDK) - iphone

A really quickly trying to add a key to a .plist. I almost have it, what is the correct version of the fourth line?
NSString *path = [[NSBundle mainBundle] pathForResource:#"Favourites" ofType:#"plist"];
NSDictionary *rootDict = [[NSDictionary alloc] initWithContentsOfFile:path];
[rootDict addKey:#"Test"]; //guessed code
[rootDict writeToFile:path atomically: YES];

You can't add elements to a NSDictionary, you need to use a NSMutableDictionary then use the setObject:forKey: method.
[rootDict setObject:someObject forKey:#"someKey"];
See NSMutableDictionary class reference

almost have it
not really.
You can't change a NSDictionary. You can't write to the mainbundle.
working code:
NSString *path = [[NSBundle mainBundle] pathForResource:#"Favourites" ofType:#"plist"];
NSMutableDictionary *rootDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
[rootDict setObject:#"Test" forKey:#"Key"];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:#"Favourites.plist"];
[rootDict writeToFile:writablePath atomically: YES];
[rootDict release];

Related

Creating an array of dictionaries plist

I am creating a plist of dictionaries. The plist starts off as empty, and then I do this:
NSMutableArray *favouritesList = [[NSMutableArray alloc] initWithContentsOfFile:path];
[favouritesList addObject:thisPlace]; // where thisPlace is some NSDictionary
[favouritesList writeToFile:path atomically:YES];
When I immediately do:
NSArray *savedFav = [[NSArray alloc] initWithContentsOfFile:path];
NSLog(#"%#", savedFav);
I get an empty array. Why is this? Why isn't it writing properly? I am setting up the plist correctly, I debugged that. But I cannot add a dictionary to it.
The plist is just an empty plist with a root that's an array
EDIT:
Here is how I construct my path:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"favourites.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:path]) {
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:#"favourites" ofType:#"plist"];
[fileManager copyItemAtPath:sourcePath toPath:path error:nil];
}
I do something like below. I add an object using a key. Maybe that's why it's not working.
static NSMutableDictionary *dictionaryStore;
+(void)initialize{
if(dictionaryStore == nil){
dictionaryStore = [[NSMutableDictionary alloc] initWithContentsOfFile:[self getFilePath]];
if(dictionaryStore == nil)
dictionaryStore = [NSMutableDictionary new];
}
}
+(NSString *)getFilePath{
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [rootPath stringByAppendingPathComponent:#"filename.plist"];
return plistPath;
}
+(NSString *)getValueForKey:(NSString *)key{
[self initialize];
return [dictionaryStore objectForKey:key];
}
+(void)setValue:(NSString *)value forKey:(NSString *)key{
[self initialize];
[dictionaryStore setValue:value forKey:key];
}
+(BOOL)save{
[self initialize];
return [dictionaryStore writeToFile:[self getFilePath] atomically:YES];
}
Edit:
So to save a value, I do:
[WAStore setValue:myValue forKey:myKey];
BOOL isSuccessful = [WAStore save];
WAStore is the class name. myValue can be most data types (NSManagedObjectModels won't work). myKey is any NSString.

How to get data from property list into an NSArray programmatically?

I have generated a property list which save some hospital names. Now I want to get the names into an array from that plist. please help me. Thanx in advance.
NSString* plistPath = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"plist"];
contentArray = [NSArray arrayWithContentsOfFile:plistPath];
try this
Try this
NSMutableDictionary* dictionary = [[[NSMutableDictionary alloc] init] autorelease];
NSError *error;
// Look in Documents for an existing plist file
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* metadataPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"Metadata.plist"]];
[metadataPlistPath retain];
// If it's not there, copy it from the bundle
NSFileManager *fileManger = [NSFileManager defaultManager];
if ( ![fileManger fileExistsAtPath:metadataPlistPath] ) {
NSString *pathToSettingsInBundle = [[NSBundle mainBundle]
pathForResource:#"Metadata" ofType:#"plist"];
[fileManger copyItemAtPath:pathToSettingsInBundle toPath:metadataPlistPath error:&error];
}
//Now read the plist file from Documents
NSString* myPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"Metadata.plist"] ];
dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:myPlistPath];
return dictionary;
}
//fetch the data based on key
- (NSMutableArray*) fetchMetadataArrayForKey:(NSString*)aKey {
NSMutableArray* arrCategories = [[[NSMutableArray alloc] init] autorelease];
NSMutableDictionary* dictionary = [self fetchMetadata];
arrCategories = [dictionary valueForKey:aKey];
return arrCategories;
}

reading from plist issue

I have a plist which is an array, the file name is called startups.plist. I tried to read it into an array by the following code:
NSString *path = [[NSBundle mainBundle] pathForResource:#"startups" ofType:#"plist"];
NSMutableArray * wordList = [[NSMutableArray alloc] initWithContentsOfFile:path];
However, wordList is always 0 here. Printed the path when testing on device, and it gives me:
/var/mobile/Applications/CCBF94D9-389C-4D63-B023-F39653FDCEF4/My.app/startups.plist
Here's what the structure looks like of the plist:
the size of the array is 0.
What am I doing wrong here?
initWithContentsOfFile: will not open plist file. Here is a sample:
NSString *errorDesc = nil;
NSPropertyListFormat format;
NSString *path = [[NSBundle mainBundle] pathForResource:#"startups" ofType:#"plist"];
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:path];
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization
propertyListFromData:plistXML
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&errorDesc];
NSLog(#"%#",[temp objectForKey:#"Root"]);
You have to use NSDictionary since your plist is a Dictionary which has a key Root which is an array.
NSString *path = [[NSBundle mainBundle] pathForResource:#"startups" ofType:#"plist"];
NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
NSMutableArray *wordList = (NSMutableArray *)[dict objectForKey:#"Root"];
I'm not sure about casting to NSMutableArray. Maybe you have to do
NSMutableArray *wordList = [NSMutableArray arrayWithArray:(NSArray*)[dict objectForKey:#"Root"]]

NSMutableDictionary

How to use NSMutable Dictionary in another class for read and write data from plist file in iphone....
Any Ideas?
As you can find in in NSDictionary reference, this class has a method to create a nsdictionary from a file initWithContentsOfFile:(NSString *)path . You can do something like:
NSString *plistPath = [[NSBundle mainBundle] pathForResource:#"myDictionary" ofType:#"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
Where myDictionary is your plist name (In case of your plist is inside resource bundle).
You can write a plist on disk with the method:
[dict writeToFile:filePath atomically: YES];
Where filePath is your destination path.
See the Plist files example on this tutorial.
// Look in Documents for an existing plist file
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
myPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"%#.plist", plistName] ];
[myPlistPath retain];
// If it's not there, copy it from the bundle
NSFileManager *fileManger = [NSFileManager defaultManager];
if ( ![fileManger fileExistsAtPath:myPlistPath] ) {
NSString *pathToSettingsInBundle = [[NSBundle mainBundle]
pathForResource:plistName ofType:#"plist"];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [documentsDirectoryPath
stringByAppendingPathComponent:#"myApp.plist"];
NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];
myKey = (int)[[plist valueForKey:#"myKey"] intValue];
myKey2 = (bool)[[plist valueForKey:#"myKey2"] boolValue];
[plist setValue:myKey forKey:#"myKey"];
[plist writeToFile:path atomically:YES];

How to save a value in a plist file in iPhone?

I am new to iPhone development. I am using the below code to add the value to the plist but when check the plist after executing the code I don't see any value saved in the plist. Where did I go wrong? The plist I have created is in the resource folder.
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:#"regvalue.plist"];
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:finalPath];
[plistDict setValue:#"hello" forKey:#"choice"];
[plistDict writeToFile:finalPath atomically: YES];
For retrieving the value
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:#"regvalue.plist"];
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:finalPath];
NSString *value;
value = [plistDict objectForKey:#"choice"];
NSLog(#"the value is %#",value);
It gives only null value.
The resources folder is not writeable. You should save it into the documents folder.
Maybe you can find the answer here:
How to write data in plist?
But if you only want save some message in you app, NSUserDefaults is the better way.