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 okid 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.
精彩评论