How do you tell if a key exists for an object using Key-Value Coding?

后端 未结 4 762
予麋鹿
予麋鹿 2021-01-31 14:44

I\'d like to test whether an object has a writeable @property in the iPhone SDK.

One possible way of doing this is to check the -valueForKey: method, but that seems rat

4条回答
  •  天涯浪人
    2021-01-31 15:24

    Following on from @Jason Coco answer.

    Here is my offering on how to check specifically for the "set" selectors existence of the property you're trying to set.

    This is pure filth but it works and I've found myself using it. You've been warned..

    NS_INLINE SEL _Nonnull IBPropertySetSelectorForPropertyName(NSString*_Nonnull propertyName)
    {
    
        NSString* firstLetter = [propertyName substringToIndex:1];
        propertyName = [propertyName substringFromIndex:1];
    
        propertyName = [[NSString alloc] initWithFormat:@"set%@%@:",firstLetter.capitalizedString,propertyName];
    
        return NSSelectorFromString(propertyName);
    }
    

    Usage:

    In swift: Add the code snippet to your bridging header then:

    let key = "someKey"    
    let sel = IBPropertySetSelectorForPropertyName(key)
    
    if SOMETHING.responds(to: sel) {SOMETHING.setValue(value, forKeyPath: key)}
    

提交回复
热议问题