我看过selector as parameter in IOS帖子。但是,我想扩展这个问题。
就我而言,我正在创建一个Objective-C(不是Swift)Master / Detail应用程序,并希望使用以下init函数创建UIViewController类型的DetailController对象
在DetailViewController.h中
@interfact DetailViewController : UIViewController
- (id)initWithNibName:(NSString *)nibName withSaveSelector:(SEL)saveSelector
@end
...并在DetailViewController.m
中- (id)initWithNibName:(NSString *)nibName withSaveSelector:(SEL)saveSelector
{
self = [super initWithNibName:nibName bundle:nil];
if (self) {
UIBarButtonItem *done = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:saveSelector];
[[self navigationItem] setRightBarButtonItem:done animated:YES];
}
return self;
}
现在,我想继续重复使用上面的代码来创建不同的DetailViewControllers,并希望传递一个saveSelector函数,当用户按下“完成”按钮时将调用该函数。
现在我有另一个视图控制器
@interface AnotherViewController : UIViewController
- (void)saveSelector:(id)sender;
@end
...然后在另一个对象(即不在AnotherViewController.m代码中),我使用上面的视图控制器,就像这样...
AnotherViewController *avc = [[AnotherViewController alloc] init];
DetailViewController *dvc = [[DetailViewController alloc] initWithNibName:@"AnotherViewController" withSaveSelector:@selector(???)];
我该怎么办?所以我可以将AnotherViewController :: saveSelector()函数传递给DetailViewController?
我希望这是有道理的。
答案 0 :(得分:1)
将您的方法更改为:
DetailViewController *dvc = [[DetailViewController alloc] initWithNibName:@"AnotherViewController" withSaveSelector:@selector(saveSelector:) forTarget:avc];
并称之为:
DetailViewController.m
在- (id)initWithNibName:(NSString *)nibName withSaveSelector:(SEL)saveSelector forTarget:(id)target
{
self = [super initWithNibName:nibName bundle:nil];
if (self) {
UIBarButtonItem *done = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:target
action:saveSelector];
[[self navigationItem] setRightBarButtonItem:done animated:YES];
}
return self;
}
$query = $conn->prepare("select * from contents JOIN users ON contents.publisher_id = users.id
WHERE trend = 1 order by content_id desc limit 20");
$query->execute();
$data = array();
while($result= $query->fetch(PDO::FETCH_ASSOC)) {
$data[] = array("content_id" =>$result['content_id'],
"publisher_id" =>$result['publisher_id'],
"publisher_name"=>$result['name'],
"publisher_rank"=>$result['rank'],
"title" =>$result['title'],
"category" =>$result['category'],
"type" =>$result['type']
);
};
echo json_encode($data);