预处理
1.文件包含
#import <Foundation/Foundation.h>
2.宏定义
#define JR_PI 3.14
#define JR_MAX(a,b) ((a>b)?(a):(b)) //得到两个数中较大值
#define JR_SQUARE_1(n) n*n //求数字的平方
#define JR_SQUARE_2(n) (n)*(n) //求数字的平方
#define JR_HELLO @"hello world";
3.条件编译
#import <Foundation/Foundation.h>
#define JR_COUNT 10
int main(int argc, const char * argv[]) {
@autoreleasepool {
#if defined(JR_COUNT)
NSLog(@"定义了 COUNT 这个宏");
#endif
#if defined(JR_MAX)
NSLog(@"没有定义了 JR_MAX 这个宏");
#endif
#if JR_COUNT==1
NSLog(@"JR_COUNT=1");
#elif JR_COUNT==2
NSLog(@"JR_COUNT=2");
#elif JR_COUNT==3
NSLog(@"JR_COUNT=3");
#else
NSLog(@"JR_COUNT=%i",JR_COUNT);
#endif
}
return 0;
}
SEL
一个关键字,就像int,long一样,它声明了一种类型:类方法指针。
#import "ViewController.h"
@interface ViewController ()
{
SEL myLog;
}
@end
传递方式:
@interface ViewController ()
{
SEL myLog;
}
@end
@implementation ViewController
- ( void )viewDidLoad {
[super viewDidLoad];
#第一种
myLog = @selector(myLogL);
//通过performSelector来执行方法
#第二种
myLog = NSSelectorFromString(@ "myLogN" );
[self performSelector:myLog]; //打印 “myLog”
}
-( void )myLogL{
NSLog(@ "myLog" );
}
例子
//Mybutton.h中
#import <UIKit/UIKit.h>
@interface Mybutton : UIButton
-( void )addMyTarget:(id)target action:(SEL)action;
@end
//Mybutton.m中
#import "Mybutton.h"
@implementation Mybutton
{
SEL _action;
id _target;
}
-( void )addMyTarget:(id)target action:(SEL)action{
_target=target;
_action=action;
}
-( void )touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[_target performSelector:_action];
}
@end
//外部
- ( void )viewDidLoad {
[super viewDidLoad];
Mybutton * btn = [[Mybutton alloc]initWithFrame:CGRectMake(100, 100, 60, 60)];
btn.backgroundColor=[UIColor redColor];
[btn addMyTarget:self action:@selector(click)];
[self.view addSubview:btn];
}
-( void )click{
NSLog(@ "点击了btn" );
}