objective c 的performSelector 与block

来源:互联网 发布:nginx 域名配置 编辑:程序博客网 时间:2024/06/04 17:43
   //无参数                -(void)noParam;                //一个参数                -(void)oneParam:(NSString *)oneParam;                //两个参数                -(void)oneParam:(NSString *)oneParam twoParam:(NSString*)twoParam;                //最多支持两个参数                        [TestClass performSelector:@selector(noParam)];                [TestClass performSelector:@selector(oneParam:)withObject:@"参数1"];                [TestClass performSelector:@selector(oneParam:twoParam:)withObject:@"参数1" withObject:@"参数2"];                                //多参数                //最多只能支持两个参数,因此多参数只能别想办法                //比如将参数放在数组中,然后使用一个参数的使用方法可以实现

SEL:

1、SEL其实是对方法的一种包装,将方法包装成一个SEL类型的数据,去找对应的方法地址。找到方法地址就可以调用方法

a、把test1  test2包装成SEL类型的数据

b、根据方法地址调用对应的方法

        SEL s1 = @selector(test1);        SEL s2 = NSSelectorFromString(@"test2");//通过NSString定义SEL        [Test performSelector:s1];        NSString *str = NSStringFromSelector(s1); //这样str=@“test1”;

Blocks的定义以及使用:

 int (^MySum)(int, int) = ^(int a, int b) {              return a+b;          };         int b = MySum(1,2);


Block可以访问局部变量,但是不能修改但是如果要修改就要在局部变量前加关键字:__block

int a = 10;  __block int b = 20;        void (^block)();        block = ^{  NSLog(@"%d", a);    // 错误: block不能访问局部变量  NSLog(@"%d", b);    // 正确: block可以访问用__block修饰的局部变量            a = 100;    // 错误: block不能修改局部变量的值  b = 100;    // 正确: block不能修改用__block修饰的局部变量的值  }  


Block 可以使用typedef

typedef (^MySum)(int,int);          MySum sum;        sum= ^(int a,int b) {              return a + b;          };

如果没有形参括号可以省略

p.test = t;        void (^MyBlock)() = ^{              NSLog(@"Block");         };         MyBlock();


苹果官方建议尽量多用block,因为效率高。




0 0
原创粉丝点击