开发者

How to check if an id property mutated

开发者 https://www.devze.com 2023-03-31 20:01 出处:网络
As part of learning Objective C I had an excerise where a a third party library returns a random object . I then need to check if it is an instance of UIView and then check is it has back groundColor

As part of learning Objective C I had an excerise where a a third party library returns a random object . I then need to check if it is an instance of UIView and then check is it has back groundColor proprty . If it does then I set it to some random color.

Code below does that but I am curious that what if it was a mute object and even if you have this property you can not change it how would you test for that.

here is the code which run fine as such without problems but just curious also let me know any thing else you see I am doing wrong. Like I said end result is ok

id myView = [RandomObjectFactory randomNSObject];
    UIView* parentView =[self view];
    if ([myView isKindOfClass:[UIView class]])
    {
        UIView* uiView = (UIView*) myView;
        SEL sel = @selector(backgroundColor);
        if([uiView respondsToSelector:sel])
        {
            UIColor *textColour = [UIColor  colorWithRed:0.1 green:0.2 blue:0.1 alpha:1.0];
            [uiView setBackgroundC开发者_高级运维olor:textColour];
        }

        [parentView addSubview:uiView];
    }


You should check for selector

 setBackgroundColor: 

as well, this would ensure that the property is not read only. You can then check the result of backgroundColor before and after you call setBackgroundColor, to ensure that the value has indeed been set. In this case you know it will be as you are aware of the properties of UIView but I imagine you are looking for a more general solution.

0

精彩评论

暂无评论...
验证码 换一张
取 消