Difference between objectForKey and valueForKey?

后端 未结 5 2162
清歌不尽
清歌不尽 2020-11-22 13:25

What is the difference between objectForKey and valueForKey? I looked both up in the documentation and they seemed the same to me.

5条回答
  •  孤独总比滥情好
    2020-11-22 14:29

    As said, the objectForKey: datatype is :(id)aKey whereas the valueForKey: datatype is :(NSString *)key.

    For example:

     NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObject:@"123"],[NSNumber numberWithInteger:5], nil];
    
     NSLog(@"objectForKey : --- %@",[dict objectForKey:[NSNumber numberWithInteger:5]]);  
        //This will work fine and prints (    123    )  
    
     NSLog(@"valueForKey  : --- %@",[dict valueForKey:[NSNumber numberWithInteger:5]]); 
        //it gives warning "Incompatible pointer types sending 'NSNumber *' to parameter of type 'NSString *'"   ---- This will crash on runtime. 
    

    So, valueForKey: will take only a string value and is a KVC method, whereas objectForKey: will take any type of object.

    The value in objectForKey will be accessed by the same kind of object.

提交回复
热议问题