2

I'm trying to learn more about macro programming for Obj-C, as I have seen quite a bit of cool stuff done with it. Is it is possible to accomplish the following with a one-line macro?

MyNewViewController *newVC = [[MyNewViewController alloc] init]; [self.navigationController pushViewController:newVC animated:YES]; [newVC release]; 

Something like:

PushToNavController(@"MyNewViewController",YES); 

Thanks

5
  • Consider using a function for this. It's too big for macros. Commented Feb 15, 2011 at 20:10
  • 6
    and an order of magnitude more difficult to debug with limited/no increase in functionality. Commented Feb 15, 2011 at 20:17
  • 5
    Macros are enticing, but ultimately suck for this kind of thing. They make debugging harder and they make code comprehension more difficult. Not only do you have to learn what the Macro means in the first place, but you have to also know the details of the innards. And they can be a pain when refactoring; crap, I need to change a detail of this macro use in this spot, I wonder if that'll break use everywhere else?!?! Commented Feb 15, 2011 at 20:43
  • 1
    This isn't a cool thing to do in a macro, at all. When there's something you want to do and it can't be done with a function, but it can be done in a macro, that's the time to use it. I'm not being specific because I can't even think of any good scenarios to use a macro right now. Commented Aug 19, 2014 at 23:26
  • A function would be better and you will get some cool color marks in you IDE. Macro looks weird, hard to ready etc. so for more complicated things use functions instead of macros. Commented Apr 19, 2015 at 21:39

1 Answer 1

5

Sure:

#define PushToNavController(_n,_a) { \ _n *__vc = [[(_n) alloc] init]; \ [self.navigationController pushViewController:__vc animated:(_a)]; \ [__vc release]; \ } 

And then you'd use it like this:

PushToNavController(MyNewViewController, YES); 

But.. why do you want to do this?

Sign up to request clarification or add additional context in comments.

1 Comment

Just playing around and learning the macro syntax. Other motivation: I read an article on Matt Gallagher's blog (cocoawithlove.com/2008/03/core-data-one-line-fetch.html) that showed how to do a one-line fetch with a category on NSManagedObject. I like this a lot and have used it, but I have all of these #import "NSManagedObject-Utilities.h" statements throughout my code. So why not make it a macro?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.