如何使用ObjectForKey从NSDictionary中获取Object

时间:2013-03-07 08:03:37

标签: iphone ios

我有3 NSMutableArray s:_parssedArrayOfName_parssedArrayOfbirthdate_CopyOFSelectedFaceBookFriends

_parssedArrayOfName中有许多名称,如下所示

2013-03-07 13:15:40.003 birthdate reminder 2[1102:15803] asdas{
        (
        "Nishith Shah",
        "Rupal Shah",
        "Viral Nagori",
        "Malay Shah",
        "Heather Joy",
        "Jatin Patel",
        "Bhushan H Trivedi",
        "Umang Patel",
        "Harshal Arolkar",
        "Nida Shaikh",
        "Yuriko Ramirez",
        "Aysu Can",
        "Bhargav Khatana",
        "Rahul Vador",
        "Viral Dave",
_parssedArrayOfbirthdate中的

有下面的生日

13-03-07 13:15:29.833 birthdate reminder 2[1102:15803]  this is what im here(
        (
        "<null>",
        "07/27",
        "06/11/1980",
        "08/22/1990",
        "<null>",
        "03/17/1985",
        "<null>",
        "10/17/1989",
        "<null>",
        "07/20",
        "12/08",
        "04/14/1992",
        "10/16",
        "<null>",

_CopyOFSelectedFaceBookFriends 是用户选择的朋友列表只是为了说Anand Kapadiya

我将NSDictionary名称中的所有姓名和出生率添加为关键和生日值作为值 然后我想使用ObjectForKey从这本词典中获取anand kapadiya birthdate:

但我得到空值我的代码如下所示plz帮助我

注意:不同数组中的Birthdate和Names数相同,所选数组值总是在names数组中

注意2:可能是这个问题的原因吗?在选择器名称中没有&#34;&#34;在名称数组中,所有名称都使用&#34;&#34;

注3:你可以看到我的生日数组包含空值,这可能是问题吗?

NSArray *objArr = [[NSArray alloc] initWithArray:_parssedArrayOfbirthdate];
NSArray *keyArr =[[NSArray alloc] initWithArray:_parssedArrayOfName];
NSArray *selector =[[NSArray alloc] initWithArray:_CopyOFSelectedFaceBookFriends];     NSDictionary *dic = [[[NSDictionary alloc] autorelease] initWithObjects:objArr forKeys:keyArr];
NSLog(@"asdas%@",dic.description);
 NSMutableArray *matches = [NSMutableArray array];
 for (NSString *key in selector) {
 NSLog(@" see it%@",key);
  NSMutableArray *array1 = [dic objectForKey:key];
        NSLog(@" matched%@",array1);
        [matches addObject:array1];
        NSLog(@" matched%@",matches);

1 个答案:

答案 0 :(得分:0)

您的问题和此代码很难理解。但是,我认为问题是密钥字符串并不总是代表dic字典中的有效密钥。如果您要检查选择器数组的哪些元素是有效键,则需要先使用if语句检查它们是否存在。

您的代码中也有自动释放,但所有内存管理都应由ARC处理。

试试这个:

NSArray *birthdates = [[NSArray alloc] initWithArray:_parssedArrayOfbirthdate];
NSArray *names =[[NSArray alloc] initWithArray:_parssedArrayOfName];
NSArray *fbFriends =[[NSArray alloc] initWithArray:_CopyOFSelectedFaceBookFriends];    
NSMutableArray *matches = [[NSMutableArray alloc] initWithCapacity:1];    

NSDictionary *birthdayDictionary = 
[[NSDictionary alloc] initWithObjects:birthdates forKeys:names];

NSLog(@"asdas%@",birthdayDictionary.description);
NSStrging *birthday;
for (NSString *friend in fbFriends) {
    NSLog(@"see it %@",friend);
    if ([birthdayDictionary objectForKey:friend])
    {
        NSLog(@"matched %@",birthday);
        [matches addObject:birthday];
        NSLog(@"matched %@",matches);
    }
}