Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios, KVC, why doesn't it invoke countOf<Key> when i invoke [[MyObject valueForKey:"MyArray" ] count]

..................

    Environment:OSX10.8, Xcode4.5
    Reference:
    https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual
    /KeyValueCoding/Articles/SearchImplementation.html#//apple_ref/doc/uid
    /20000955-CJBBBFFA

    If the countOf method and at least one of the other two possible methods are 
    found, a collection proxy object that responds to all NSArray methods is 
    returned. Each NSArray message sent to the collection proxy object will result 
    in some combination of countOf, objectInAtIndex:, and AtIndexes: messages being 
    sent to the original receiver of valueForKey:.

My steps:

1) Create a property for NSArray* arrs in MyObject.h.

2) in MyObject.m

@implementation MyObject
- (void)setArrs:(NSArray*)arrs
{ _arrs=arrs; }

- (NSUInteger) countOfArrs
{ NSLog("Im here");
  return 0;}

- (id) objectInArrsAtIndex:(NSUInteger)index
{ NSLog(@"objectInArrs");
  return nil;
}

@end

3) Testing code

MyObject* obj=[[MyObject alloc] init];
NSArray* arr=[NSarray arrayWithObjects:@"abc",nil];
[obj setArrs:arr];
NSLog(@"%d",[[obj valueForKey:@"arrs"]count]);
NSLog(@"%@",[[obj valueForKey:@"arrs"] objectobjectAtIndex:0])

My Question:

I expect it to invoke countOfArrs and objectInArrsAtIndex: automatically, however, it didn't. All it does is return the normal NSArray, shows count quantity by 1 and 'abc'.

I didn't find any helpful samples,or maybe i misunderstand what the doc says, don't I?

My tangue language is not English, hope i didn't make any ambitious issues.

like image 353
MarcusHe Avatar asked Jan 30 '26 04:01

MarcusHe


1 Answers

You have implemented more functionality than what is needed. Your @property declaration is adding the -<key> getter and -set<Key> accessor. As you were able to find out, your getter (called by valueForKey:@"arrs") is returning the actual NSArray assigned to the property which returns its count and object.

The guide you linked to has the reason why this didn't work in step 1 and step 2 of the Default Search Pattern for valueForKey: section.

Basically, your -countOf<Key> and -objectIn<Key>AtIndex: methods are only called when there isn't either a -<key>, -get<Key> or -is<Key> methods.

In order to get this to work, you need to remove the getter by removing the @property declaration, and then you'll need to add an instance variable to save your array.

Make this your interface and it should work

@interface MyObject : NSObject {
  NSArray *_arrs;
}
@end
like image 66
Dave FN Avatar answered Feb 01 '26 18:02

Dave FN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!