What does “macro” mean in Objective-C?

前端 未结 4 1488
被撕碎了的回忆
被撕碎了的回忆 2021-02-02 17:35

I am new to iOS development and I just want to know the meaning of macro in Objective-C?

I have found that \"macro\" is used with #define but still do not get its meanin

4条回答
  •  北海茫月
    2021-02-02 18:05

    A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. There are two kinds of macros. They differ mostly in what they look like when they are used. Object-like macros resemble data objects when used, function-like macros resemble function calls.

    An object-like macro is a simple identifier which will be replaced by a code fragment. It is called object-like because it looks like a data object in code that uses it. They are most commonly used to give symbolic names to numeric constants.

    You create macros with the ‘#define’ directive. ‘#define’ is followed by the name of the macro and then the token sequence it should be an abbreviation for, which is variously referred to as the macro's body, expansion or replacement list. For example,

     #define BUFFER_SIZE 1024
    

    defines a macro named BUFFER_SIZE as an abbreviation for the token 1024. If somewhere after this ‘#define’ directive there comes a Objective C statement of the form

     foo = (char *) malloc (BUFFER_SIZE);
    

    The Objective C compiler will see the same tokens as it would if you had written

     foo = (char *) malloc (1024);
    

    You can also define macros whose use looks like a function call. These are called function-like macros. To define a function-like macro, you use the same ‘#define’ directive, but you put a pair of parentheses immediately after the macro name. Like:

    #define isIphone([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
    
    #define GetImage(imageName) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]     pathForResource:imageName ofType:@"png"]]
    

提交回复
热议问题