まあタイトルまんまです
まあタイトルまんまです。
セレクタ指定でメソッド呼び出しを行う際に、文字列からセレクタを生成したい場合。
そんなときはNSSelectorFromString を使えばOKです。
例:セルごとに異なるメソッドを呼び出したい
例えば、UITableViewCell に配置したUISwitch があるとします。
そして、セルごとにスイッチの切り替えで異なるメソッドを呼び出させたい場合。 *01【異なるメソッドを呼び出したい】
共通関数を1つ作って、そこから振り分けさせればいいんじゃねーの?ってツッコミはスルーの方向で。
- (void)method1 {
NSLog(@"hoge");
}
- (void)method2 {
NSLog(@"piyo");
}
- (void)method3 {
NSLog(@"fuga");
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString* titleText = @"";
NSString* selectorString = @"";
BOOL switchValue = NO;
if ( indexPath.section == 0 ) {
if ( indexPath.row == 0 ) {
titleText = @"call hoge:";
selectorString = @"method1:";
}
else if ( indexPath.row == 1 ) {
titleText = @"call piyo:";
selectorString = @"method2:";
}
else if ( indexPath.row == 2 ) {
titleText = @"call fuga:";
selectorString = @"method3:";
}
}
static NSString* cellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
cell.textLabel.text = titleText;
UISwitch* boolSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
[boolSwitch setOn:switchValue];
[boolSwitch addTarget:self action:NSSelectorFromString(selectorString) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = boolSwitch;
}
上記の様にすると、セルに配置されたスイッチごとに異なるメソッドを呼び出すことが可能です。
脚注
| ↩01 | 【異なるメソッドを呼び出したい】 共通関数を1つ作って、そこから振り分けさせればいいんじゃねーの?ってツッコミはスルーの方向で。 |
|---|