Objective-C 筆記》NSSelectorFromString

在 Objective-C 裡,可以使用 NSSelectorFromString() 函式把一個 NSString 轉換成 Selector,這樣就可以在執行期才決定要傳送的訊息:

SEL aSelector = NSSelectorFromString(@"redColor");  // 把一個字串轉換成 Selector

例如,有一個儲存顏色字串的 Array :

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // color string array
        self.items = @[@"Red", @"Green", @"Blue", @"Yellow", @"Orange"];
    }
    return self;
}

然後在一個 TableView 裡顯示這些顏色字串與顏色:

#pragma mark - UITableView Data Source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    
    // 利用字串產生 Selector
    SEL colorMethod = NSSelectorFromString([NSString stringWithFormat:@"%@Color", [_items[indexPath.row] lowercaseString]]);

    if ([UIColor respondsToSelector:colorMethod]) {
        // 發送訊息
        cell.textLabel.textColor = [UIColor performSelector:colorMethod];
    }
    
    cell.textLabel.text = _items[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}

執行結果會像這樣: