سؤال

I have seen a lot of tutorials about adding to a plist file but I can't seem to correctly insert nested tags into the plist file. I want to add the following lines to my Info.plist file

<key>AppTag</key> <array>
     <string>hidden</string> </array>


NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile:@"/Users/me/Desktop/Info2.plist"] mutableCopy];

  [plist setObject:@"AppTag" forKey:@"key"];
  [plist setObject:@"hidden" forKey:@"string"];

    [plist writeToFile:@"/Users/me/Desktop/Info2.plist" atomically:YES];
    [plist release];
هل كانت مفيدة؟

المحلول

You need to set an array of strings as the object for key @"AppTag", like so:

NSArray *strings = @[@"hidden"];
plist[@"AppTag"] = strings;

نصائح أخرى

What you need to do is add strings to your array, and then the array to the dictionary of the file. In the following example, I'm adding some words and their definitions to a file called WordList.plist:

NSArray *values = [[NSArray alloc] initWithObjects:word.name, word.definition, nil];
NSArray *keys = [[NSArray alloc] initWithObjects: NAME_KEY, DEFINITION_KEY, nil];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjects:values forKeys:keys];
[wordsListArray addObject:dict];

NSString *destinationPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
 NSUserDomainMask, YES) lastObject];
destinationPath = [destinationPath stringByAppendingPathComponent:@"WordList.plist"];
[wordsListArray writeToFile:destinationPath atomically:YES];

I hope this helps.

Also, I think this is the part that's not working fine: @"/Users/me/Desktop/Info2.plist"

Try NSLogging.

You can try following code

-(NSString *) datafilepath{



NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documents=[path objectAtIndex:0];
return [documents stringByAppendingFormat:@"/Info2.plist"]; // you can change the path to desktop
}

Under ViewDidLoad or any method

NSString *filepath3=[self datafilepath];
if ([[NSFileManager defaultManager]fileExistsAtPath:filepath3]) {
    pricedict=[[NSMutableDictionary alloc]initWithContentsOfFile:filepath3];
}

[pricedict setObject:@"AppTag" forKey:@"key"];
[pricedict setObject:@"hidden" forKey:@"string"];

[pricedict writeToFile:pngfilepath atomically:YES];

Hope this helps.. Happy coding 

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top