makeObjectsPerformSelector的使用
NSArray 类定义的方法:
makeObjectsPerformSelector:
这是数组用的方法,类似于for循环。
makeObjectsPerformSelector:@selector(method:)
意为数组中的每个元素都执行method方法
makeObjectsPerformSelector:@selector(method:) withObject:obj
表示数组中的每个元素都执行method方法,并把obj对象作为参数传到method方法中。
注意:
这是 NSArray和NSSet的两个方法,相信大家很少用,它类似于 for循环,但有效率高于for循环
makeObjectsPerformSelector:类似于NSNotifation机制,并发的执行同一件事,不能像for循环那样区别对待
所以参数 argument 必须是非基本类型 ,如果要是用基本类型 请转换程 NSNumber 或者NSValue。
用法:如果一个数组objArr中存储了一组有hide属性的对象,需要将数组里所有对象的hide全部赋值为真,就可以这么写:
[self.dataAray makeObjectsPerformSelector:@selector(setHidden:) withObject:@(NO)]; [self.dataAray makeObjectsPerformSelector:@selector(setHidden:)];
代码如下:
// // ViewController.m // Demo1 // // Created by 思 彭 on 2017/4/6. // Copyright © 2017年 思 彭. All rights reserved. // #import "ViewController.h" #import "Model.h" @interface ViewController () @property (nonatomic, strong) NSArray *dataAray; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSMutableArray *array = [NSMutableArray array]; for (NSInteger i = 0; i < 10; i++) { Model *model = [[Model alloc]init]; model.hidden = YES; [array addObject:model]; } self.dataAray = [array copy]; NSLog(@"变换前的model:"); for (Model *model in self.dataAray) { NSLog(@"%d",model.hidden); } UIButton *button = [UIButton buttonWithType: UIButtonTypeCustom]; button.frame = CGRectMake(100,100,100,50); button.layer.borderColor = [UIColor lightGrayColor].CGColor; button.layer.borderWidth = 0.5; [button setTitle:@"变换" forState:UIControlStateNormal]; [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal]; button.titleLabel.font = [UIFont systemFontOfSize:14]; [button addTarget:self action:@selector(buttonDidClick) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; } - (void)buttonDidClick { // [self.dataAray makeObjectsPerformSelector:@selector(setHidden:) withObject:@(NO)]; [self.dataAray makeObjectsPerformSelector:@selector(setHidden:)]; NSLog(@"变换后的model:"); for (Model *model in self.dataAray) { NSLog(@"%d",model.hidden); } } @end
// // Model.h // Demo1 // // Created by 思 彭 on 2017/4/6. // Copyright © 2017年 思 彭. All rights reserved. // #import <Foundation/Foundation.h> @interface Model : NSObject @property (nonatomic, assign) BOOL hidden; @end
实现效果打印如下:
这种方式还是很快捷呀,不过还是有局限...