【发布时间】:2011-06-04 11:32:25
【问题描述】:
我可以只从 plist 中读取没有值的键吗?如果我知道值,我可以读取键吗?
【问题讨论】:
-
如果不同的键有相同的值怎么办?那么必须发生什么?
-
@WTP: 没有Keys具有相同的值,这种情况不会发生
标签: ios iphone ipad plist key-value
我可以只从 plist 中读取没有值的键吗?如果我知道值,我可以读取键吗?
【问题讨论】:
标签: ios iphone ipad plist key-value
阅读.plist:
NSString *path = [[NSBundle mainBundle] pathForResource:@"myPlist" ofType:@"plist"];
NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
获取所有键和所有值:
NSArray* allmyKeys = [myDictionary allKeys];
NSArray* allmyValues= [myDictionary allValues];
获取值对象的所有键:
NSArray* allmyKeys = [myDictionary allKeysForObject:myValueObject];
【讨论】:
myDictionary 应该是NSDictionary,而不是NSMutableDictionary。
作为替代方案,您可以使用返回的allKeysForObject: 方法,
一个新数组,其中包含对应于字典中所有出现的 anObject 的键。如果没有找到匹配 anObject 的对象,则返回一个空数组。
您可以通过调用objectAtIndex: 方法从该数组中获取键。
【讨论】:
使用-[NSDictionary allKeysForObject:]*。
NSArray *keys = [myDict allKeysForObject:@"My Value"];
if ([keys count] != 0) { // to prevent out-of-bounds crashes
NSString *key = [keys objectAtIndex:0];
return key;
} else {
return nil;
}
*不知道为什么它返回一个 NSArray 对象而不是一个 NSSet 对象,因为键没有排序。哦,好吧。
【讨论】:
为了读取应用程序安装文件夹中的值:
NSString *PListName=@"ExamplePlist";
NSString *_PlistNameWithExtension=[NSString stringWithFormat:@"%@.plist",PlistName];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:_PlistNameWithExtension]; //3
NSDictionary *myDictionary = [[NSDictionary alloc] initWithContentsOfFile:path];
NSLog(@"%@",[myDictionary description]);
NSArray *AllKeys=[myDictionary allKeys];
Jhaliya 的方法对我不起作用,然后我尝试了这种方法。
【讨论】: