valueforkey when object property is readonly and Calculated(derived)

I am having trouble calling valueforkey method on a property that is calculated. For example:

@interface Value : NSObject
@property(nonatomic,getter = toString,readonly)NSString *stringVal;

-(NSString*) toString;
@end

When I call [instanceOfValueClass valueForKey:@"stringVal"] , It says it is not key-value compliant. Exact Message is :

[ valueForUndefinedKey:]: this class is not key value coding-compliant for the key stringVal.

Does key value coding works on derived properties?

Thanks


You have set the getter method to toString , so

 [instanceOfValueClass valueForKey:@"toString"]

should work. Note that you don't have to "rename" the getter method, you could just override the default getter:

@property(nonatomic,readonly) NSString *stringVal;

- (NSString *)stringVal
{
    NSString *s = ...; // compute property value
    return s;
}

Then both instance.stringVal and [instance valueForKey:@"stringVal"] would work, with the "same key".

链接地址: http://www.djcxy.com/p/19238.html

上一篇: 检测设备是否为iPhone X

下一篇: valueforkey当对象属性是只读和计算(派生)