Hey guys, really quickly trying to add a key to a .plist, almost have it, what is the correct version of the fourth line? Thanks!
嘿伙计们,真的很快就试图在.plist中添加一个密钥,几乎拥有它,第四行的正确版本是什么?谢谢!
NSString *path = [[NSBundle mainBundle] pathForResource:@"Favourites" ofType:@"plist"];
NSDictionary *rootDict = [[NSDictionary alloc] initWithContentsOfFile:path];
[rootDict addKey:@"Test"]; //guessed code
[rootDict writeToFile:path atomically: YES];
2 个解决方案
#1
12
almost have it
几乎拥有它
not really.
不是真的。
You can't change a NSDictionary. You can't write to the mainbundle.
您无法更改NSDictionary。你不能写到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];
#2
18
You can't add elements to a NSDictionary, you need to use a NSMutableDictionary then use the setObject:forKey:
method.
您不能向NSDictionary添加元素,您需要使用NSMutableDictionary然后使用setObject:forKey:方法。
[rootDict setObject:someObject forKey:@"someKey"];
See NSMutableDictionary class reference
请参见NSMutableDictionary类引用
#1
12
almost have it
几乎拥有它
not really.
不是真的。
You can't change a NSDictionary. You can't write to the mainbundle.
您无法更改NSDictionary。你不能写到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];
#2
18
You can't add elements to a NSDictionary, you need to use a NSMutableDictionary then use the setObject:forKey:
method.
您不能向NSDictionary添加元素,您需要使用NSMutableDictionary然后使用setObject:forKey:方法。
[rootDict setObject:someObject forKey:@"someKey"];
See NSMutableDictionary class reference
请参见NSMutableDictionary类引用