在另一个 class 中执行一个选择器

Execute a selector within another class

我想在另一个控制器中创建一个 UITableViewController,并从该控制器向它传递一个方法。我已经读到这可以通过使用@selector 来实现。现在我尝试了以下方法:

TimeController.m

- (void)choseTime{
    SelectOptionController *selectController = [[SelectOptionController alloc] initWithArray:[Time SQPFetchAll] andSelector:@selector(timeSelected)];
    [self.navigationController pushViewController:selectController animated:true];
}

- (void) timeSelected{
    NSLog(@"Time selected!");
}

SelectOptionController.h

@interface SelectOptionController : UITableViewController

@property (nonatomic, strong) NSMutableArray *dataset;
@property (nonatomic) SEL selectedMethod;

-(id)initWithArray: (NSMutableArray *) myArray andSelector: (SEL) selectedMethod;

SelectOptionController.m

- (id)initWithArray: (NSMutableArray *) myArray andSelector: (SEL) selectedMethod{
    self = [super initWithStyle:UITableViewStyleGrouped];
    if(self) {
        self.dataset = myArray;
        self.selectedMethod = selectedMethod;
    }
    return self;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self performSelector:self.selectedMethod];
    [self.navigationController popViewControllerAnimated:true];
}

但是,当一个单元格被选中时,会抛出以下异常:

-[SelectOptionController timeSelected]: unrecognized selector sent to instance 0x1450f140

我在这里做错了什么?任何帮助将不胜感激。

您正在 self 上调用 timeSelected,它实际上是 SelectOptionController,但是 TimeController class.

中存在 timeSelected 方法

假设您不想将 timeSelected 移动到 SelectOptionController,您需要将对 TimeController 的引用传递给新的 SelectOptionController 并在其上调用选择器。选择器只是对方法的引用,而不是方法本身。您可能也想将其存储为弱引用。

例如

@interface SelectOptionController : UITableViewController

@property (nonatomic, strong) NSMutableArray *dataset;
@property (nonatomic) SEL selectedMethod;
@property (nonatomic, weak) TimeController *timeController;

- (id)initWithArray: (NSMutableArray *) myArray andSelector: (SEL) selectedMethod timeController:(TimeController*)timeController {
    self = [super initWithStyle:UITableViewStyleGrouped];
    if(self) {
        self.dataset = myArray;
        self.selectedMethod = selectedMethod;
        self.timeController = timeController;
    }
    return self;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.timeController performSelector:self.selectedMethod];
    [self.navigationController popViewControllerAnimated:true];
}

综上所述,以上内容将使您的代码正常工作,但这不是一个特别好的模式。我建议您查看 Prototypes and Delegates for implementing this behaviour, or if you want to pass the method itself, do some research on Blocks。但希望这能帮助您更好地理解选择器的工作原理。