So, I have this:

@interface Foo
@property(nonatomic, readonly, retain) NSArray* bars;
@end

@implementation Foo
@synthesize bars = _bars;
// ... more stuff here ...
@end

So Foo fills up bars with instances of Bar, and the instance of Foo lives in a container object. And then I say:

[container valueForKeyPath:@"foo.bars.@count"]

Which I expect to give me a nice boxed number. However I instead get:

Exception: [<Bar 0xc175b70> valueForUndefinedKey:]: this class is not key value coding-compliant for the key bars.

So, why? I wouldn't expect to have to implement anything special on Bar to make an NSArray of Bars countable, but that's what this error message is implying. The documentation only has trivial examples, but I would expect this to just work in the same manner.

有帮助吗?

解决方案

How does my code differ from yours? Because this works...

//  Foo.h
#import <Foundation/Foundation.h>

@interface Foo : NSObject
@property(nonatomic, readonly, retain) NSArray* bars;
@end


//  Foo.m
#import "Foo.h"

@interface Foo ()
// extended property decl here, to be readable, but this didn't seem to matter in my test
@property(nonatomic, retain) NSArray* bars;
@end


@implementation Foo

- (id)init {

    self = [super init];
    if (self) {
        _bars = [NSArray arrayWithObjects:@"bar one", @"bar none", nil];
    }
    return self;
}

@end

Then, in my container class:

// .h
@property (strong, nonatomic) Foo *foo;

// .m
_foo = [[Foo alloc] init];
NSNumber *c = [self valueForKeyPath:@"foo.bars.@count"];
NSLog(@"count is %@", c);

Logs => "count is 2"

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top