ios – 正确访问segue的目标视图控制器以分配协议代理

我在实现选择列表时遇到了集成segue和协议的一些问题.

在我的选择列表中.h我有

#import <UIKit/UIKit.h>

@protocol SelectionListViewControllerDelegate <NSObject>
@required
- (void)rowChosen:(NSInteger)row;
@end

@interface SelectColor : UITableViewController <NSFetchedResultsControllerDelegate>
-(IBAction)saveSelectedColor;
@property (nonatomic,strong) id <SelectionListViewControllerDelegate> delegate;
@end

在我的选择列表中.我有

@implementation SelectColori
@synthesize delegate;

//this method is called from a button on ui
-(IBAction)saveSelectedColore
{
    [self.delegate rowChosen:[lastIndexPath row]];
    [self.navigationController popViewControllerAnimated:YES];
}

我想通过从另一个表视图执行segue来访问此选择列表视图:

@implementation TableList
...
- (void)selectNewColor
{
    SelectColor *selectController = [[SelectColor alloc] init];
    selectController.delegate = (id)self;
    [self.navigationController pushViewController:selectController animated:YES];

    //execute segue programmatically
    //[self performSegueWithIdentifier: @"SelectColorSegue" sender: self];
}

- (void)rowChosen:(NSInteger)row
{
    UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error Title" message:@"Error Text" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [errorAlert show];
}

如果我使用以下方法导航到选择列表:

[self.navigationController pushViewController:selectController animated:YES];

显示警报.如果我改为使用:

[self performSegueWithIdentifier: @”SelectColorSegue” sender: self];

没有显示警报,因为,我认为,我没有将selectController传递给目标选择列表.有什么想法可以解决这个问题吗?

解决方法

使用Segue将数据传递给destinationViewController时,您需要使用该方法
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"SelectColorSegue"]) {
        SelectColor *vc = segue.destinationViewController;
        vc.delegate = self;
    }
}

来自Apple Docs

The default implementation of this method does nothing. Subclasses can override it and use it to pass any relevant data to the view controller that is about to be displayed. The segue object contains pointers to both view controllers among other information.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...