Reputation: 65
@interface MyClass: NSObject
@property NSArray *arr;
@end
@inplementation MyClass
- (instancetype) init
{
if(self = [super init])
{
self.arr = [[NSArray alloc] init];
}
return self;
}
@end
int main(int argc, char *argv[])
{
MyClass *temp = [[MyClass alloc] init];
[temp valueForKey:@"arr.count"]; //count is ivar of NSArray
return 0;
}
then console says
NSExceptions: [MyClass valueForUnfinedKey:] this class is not key value-complaint for the key arr.count
Everytime I use dot seperations, this exceptions
come out.
I tried to search web and read menu, I still don't know why, could anyone help? Thanks.
Upvotes: 0
Views: 158
Reputation: 53000
The method valueForKey:
takes a single key (property or local variable) name, it does not take a key path such as your arr.count
.
The method valueForKeyPath:
does take a key path, it effectively is a sequence of valueForKey:
calls. See Getting Attribute Values Using Keys in About Key-Value Coding.
However you example will still not work due to the way valueForKey:
is defined for NSArray
:
Returns an array containing the results of invoking valueForKey: using key on each of the array's objects.
So in your case if you try valueForKeyPath:@"arr.count"
, the arr
part of the path will return your array and then NSArray
's valueForKey:
will attempt to get the count
key for each element of the array and not for the array itself. Not what you want...
Which brings us to Collection Operators which provide key Paths which do operate on the collection, array in your case, and not its elements. The collection operator you need is @count
giving you the key path arr.@count
, so you need to call:
[temp valueForKeyPath:@"arr.@count"]
Unless this is an exercise in learning about KVC this can be shortened to:
temp.arr.count
which doesn’t have the issue of trying to apply count
to the array’s elements, and returns an NSUInteger
value rather than an NSNumber
instance.
HTH
Upvotes: 3
Reputation: 12144
It's because arr.count
is not key value-complaint of MyClass. When program runs, it cann't find any property of MyClass name arr.count
.
valueForKeyPath: - Returns the value for the specified key path relative to the receiver. Any object in the key path sequence that is not key-value coding compliant for a particular key—that is, for which the default implementation of valueForKey: cannot find an accessor method—receives a valueForUndefinedKey: message.
Upvotes: 1