如何定义宏以在ios中执行操作

时间:2016-06-06 18:26:33

标签: ios objective-c prefixheader.pch

我试图编写一个自定义宏,在调用它时会执行某些操作。

这是我的常量文件:

#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#endif


#define SHOW_VIEW [(AppDelegate*)[UIApplication sharedApplication].delegate showView]

#define HIDE_VIEW [(AppDelegate*)[UIApplication sharedApplication].delegate hideView]

我创建了一个pch文件:

#ifndef MYPrefixHeader_pch
#define MYPrefixHeader_pch

// Include any system framework and library headers here that should be included in all compilation units.
// You will also need to set the Prefix Header build setting of one or more of your targets to reference this file.

#ifdef __OBJC__
#import "MYGlobals.h"
#endif

#endif /* MYPrefixHeader_pch */

在我的视图控制器中,我试图调用宏:

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    SHOW_VIEW;
}

我在SHOW_VIEW线上看到错误:

enter image description here

2 个答案:

答案 0 :(得分:2)

将您的应用委托包含在常量标题MYGlobals.h

#import "AppDelegate.h"

我希望重新考虑这种方法,以获得更具可读性和一致性的代码。相反,您可以做的是为您的app委托实例定义一个宏。

#define MY_APP_DELEGATE ((AppDelegate *)[UIApplication sharedApplication].delegate)

然后直接调用它的方法:

[MY_APP_DELEGATE showView];
[MY_APP_DELEGATE hideView];

答案 1 :(得分:1)

您的宏中存在语法错误。

#define SHOW_VIEW [(AppDelegate*)[UIApplication sharedApplication].delegate showView];

#define HIDE_VIEW [(AppDelegate*)[UIApplication sharedApplication].delegate hideView];

您还需要在#import "AppDelegate.h"文件中加入prefix.pch