Search code examples
objective-cuiviewcastinguiimageview

how to cast or set an object of type id to another type like UIImageView or UIView


In the below code, I iterate through entries and they might be of type UIView or UIImageView. I want to do check if the uiComponent is of either the mentioned types, and then I want to proceed using that uiComponent in the code based on Whether it is a UIView or UIImageView?

I rote the below code but I can’t use the pointer object

uiComponent

After having it typed-casted??

Please let me know how to type the uiComponent object to either of the classes UIView or UIImageView and proceed programming using it

Code

 for (id uiComponent in uiviews) {
            UIView *uiView;
            UIImage *uiImageView;

         if ([AQSViewHelper isEntryOfTypeUIView:uiComponent]) {
                uiComponent = (UIView *)uiComponent;
         }
            if ([AQSViewHelper isEntryOfTypeUIImageView:uiComponent]) {
            uiComponent = (UIImageView *)uiComponent;
        }

         if (![uiComponent isHidden]) {
            …
    ..
    …
            }

Solution

  • Set your local object based on the type, then use it if it's not nil:

    for (id uiComponent in uiviews) {
        UIView *uiView;
        UIImageView *uiImageView;
    
        if ([AQSViewHelper isEntryOfTypeUIView:uiComponent]) {
            uiView = (UIView *)uiComponent;
        }
        if ([AQSViewHelper isEntryOfTypeUIImageView:uiComponent]) {
            uiImageView = (UIImageView *)uiComponent;
        }
    
        if (uiView) {
            // do what you want because it's a UIView
            if ([uiView isHidden]) {
                // ...
            }
            // etc ...
        }
        if (uiImageView) {
            // do what you want because it's a UIView
            if ([uiImageView isHidden]) {
                // ...
            }
            // etc ...
        }
    }
    

    Or, since you are already in if blocks, you can do it there:

    for (id uiComponent in uiviews) {
        if ([AQSViewHelper isEntryOfTypeUIView:uiComponent]) {
            // do what you want because it's a UIView
            UIView *uiView = (UIView *)uiComponent;
            if ([uiView isHidden]) {
                // ...
            }
            // etc ...
        }
        if ([AQSViewHelper isEntryOfTypeUIImageView:uiComponent]) {
            // do what you want because it's a UIImageView
            UIImageView *uiImageView = (UIImageView *)uiComponent;
            if ([uiImageView isHidden]) {
                // ...
            }
            // etc ...
        }
    }