John Lane
John Lane

Reputation: 1132

iOS create macro

I have a piece of code I'm using fairly often and would like to make a macro out of it. I'm not exactly sure how to do that though. Here's the code I want to use

UIImage *titleImage = [UIImage imageNamed:@"myLogo.png"];
UIImageView *titleImageView = [[UIImageView alloc] initWithImage:titleImage];
self.navigationItem.titleView = titleImageView;
[titleImageView release];

I want to define this block as a macro so I can later say for instance addImage(...); Thanks for your help.

Upvotes: 8

Views: 8341

Answers (4)

Madhava Reddy
Madhava Reddy

Reputation: 11

#define Image_Macro @"myLogo.png" UIImage *titleImage = [UIImage imageNamed:Image_Macro]; UIImageView *titleImageView =[[UIImageView alloc] initWithImage:titleImage]; self.navigationItem.titleView = titleImageView;

Upvotes: 0

Macmade
Macmade

Reputation: 54059

#define MY_MACRO( img ) \
    {\
        UIImage *titleImage = [UIImage imageNamed:img]; \
        UIImageView *titleImageView = [[UIImageView alloc] initWithImage:titleImage]; \
        self.navigationItem.titleView = titleImageView; \
        [titleImageView release];\
    }

Use it like this:

MY_MACRO( @"myLogo.png" )

The use of {} creates a scope block, which will prevent problems with variable redefinitions (if you have variables with the same name, where you use the macro).

Upvotes: 18

Ilanchezhian
Ilanchezhian

Reputation: 17478

Try the following macro

#define addImage( __imageName__)    \
UIImage *titleImage = [UIImage imageNamed:__imageName__];    \
UIImageView *titleImageView = [[UIImageView alloc] initWithImage:titleImage]; \
self.navigationItem.titleView = titleImageView; \
[titleImageView release]; \

Upvotes: 0

Antwan van Houdt
Antwan van Houdt

Reputation: 6991

use #define with the preprocessor, write a function, or write a method for your class.

Upvotes: 0

Related Questions