0

I have a method that finds the parentVC of a view:

-(UIViewController *)mainViewController {
    UIViewController *viewController = nil;
    for (UIView *next = [self superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            viewController = (UIViewController *)nextResponder;
            break;
        }
    }
    return viewController;
}

I'd like to instead be able to just use parentVC in the future, a macro I intend on making.

The only issue is, I don't know how to convert this to a macro so that I can just say something like, parentVC.view.alpha = 0.5f;

I'm assuming the macro will utilize blocks somehow so it can handle this iteration in finding the parent VC while still being able to be treated as an object? But I can't figure out how that may work.

Albert Renshaw
  • 17,282
  • 18
  • 107
  • 195
  • Possible duplicate of [Given a view, how do I get its viewController?](https://stackoverflow.com/questions/1372977/given-a-view-how-do-i-get-its-viewcontroller) – Willeke Jun 12 '18 at 14:21
  • @Willeke No, this has nothing to do with how to find a view's parent-VC, as you can see my code already does that. This is a question about how to convert a method that iteratively finds an object into a macro. The parent-VC code I provided is just an example use-case. – Albert Renshaw Jun 12 '18 at 18:44
  • An example of a macro is at the end of [this answer](https://stackoverflow.com/a/24590678/4244136). – Willeke Jun 12 '18 at 20:23
  • @Willeke Ah that is useful, thank you. However, it's not a duplicate of that question; that's just some extra that happened to be in that question; StackOverflow is set up to be an index in format, so this question remaining open will help future readers find the answer, as the proposed duplicate does not actually address the question being asked here at all in its Question Title, someone just happened to post a solution to my question in one of the answers over there as a footnote. – Albert Renshaw Jun 13 '18 at 00:50

1 Answers1

0

Was able to get it working with blocks in the form of:

((^NSObject*(void){/*logic+return here*/})())

Final Macro:

#define parentVC (\
(^UIViewController*(void){\
UIViewController *viewController = nil;\
for (UIView *next = [self isKindOfClass:[UIViewController class]]?[((UIViewController *)self).view superview]:[((UIView *)self) superview]; next; next = next.superview) {\
UIResponder *nextResponder = [next nextResponder];\
if ([nextResponder isKindOfClass:[UIViewController class]]) {\
viewController = (UIViewController *)nextResponder;\
break;\
}\
}\
return viewController;\
})()\
)
Albert Renshaw
  • 17,282
  • 18
  • 107
  • 195