使用委托将数据传回VC时属性为nil

时间:2014-01-28 05:38:07

标签: ios iphone objective-c delegates

我在xib文件中有一个视图,我加载到我的viewController - 它是一个临时视图,因此不会一直在屏幕上。但是,临时视图和主视图使用相同的视图控制器类,因为它们都在执行相同的工作。

现在,在xib视图中,我加载了第二个viewControoler - 让我们称之为viewControllerB - 这是一个带有197个单元格的UITableView。选择单元格后,视图将被取消,单元格的值将返回到viewControllerA。

viewControllerB在故事板上。

以下是我使用的代码:

viewControllerB(VC我需要回来的数据)

代表协议:

@protocol CountrySelectedDelegate <NSObject>

-(void)selectedCountry: (id)countryReturned;

@end

@property (strong, nonatomic) id <CountrySelectedDelegate> myDelegate;

然后在.m文件中:

设置代理:

ViewControllerA *viewA = [[ViewControllerA alloc]init];
    self.myDelegate = viewA;

然后我在相同的文件中调用委托;

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    [[self myDelegate] selectedCountry:indexPath.row];


    [self dismissViewControllerAnimated:YES completion:nil];

}

现在在viewControllerA:

pragma mark - CountrySelected Delegate

-(void)selectedCountry:(id)countryReturned
{
    self.testInt = countryReturned;


}

现在这个方法确实被委托调用了。在控制台中查看:countryReturned是正确的值。完成此方法后,self.testInt也是正确的值。

然后,在我的viewWillAppear方法中,我只是再次检查该值,看它是否与NSLog打印相同。

viewWillAppear方法中的值总是为nil(或者我检查它的任何其他地方) - 我尝试过使用NSMutableString和NSString - 总是为零。

为什么我的属性/实例变量设置为nil?

更新

这是我展示viewControllerB

的方式
- (IBAction)countrySelect:(UIButton *)sender
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
    UITableViewController *vc = [sb instantiateViewControllerWithIdentifier:@"CountrySelection"];
    vc.modalTransitionStyle = UINavigationControllerOperationPop;
    [self presentViewController:vc animated:YES completion:NULL];
}

2 个答案:

答案 0 :(得分:1)

ViewB上执行以下操作我猜你已经完成了

@protocol CountrySelectedDelegate <NSObject>

-(void)selectedCountry: (NSInteger)countryReturned;

@end

@property (week, nonatomic) id <CountrySelectedDelegate> myDelegate;

并在didSelectRowAtIndexPath

if ([[self myDelegate] respondsToSelector:@selector(selectedCountry:)]) 
{
    [[self myDelegate] selectedCountry:indexPath.row];
}

ViewA

  1. 遵守协议

    @interface ViewA : UIViewController < CountrySelectedDelegate >
    
  2. 创建电话ViewB

    ViewB *viewBObjc=[[ViewB alloc] init];
    [viewBObjc setMyDelegate:self];
    [[self navigationController] presentViewController:ViewB animated:YES completion:Nil];
    
  3. ViewA

    上实施委托
    -(void)selectedCountry: (NSInteger)countryReturned
    {
        NSLog(@"Country Id is :%d", countryReturned);
    }
    

答案 1 :(得分:0)

试试这个,

通过

设置委托
//in ViewControllerB
self.myDelegate = [self parentViewController];

- (IBAction)countrySelect:(UIButton *)sender
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
    ViewControllerB *vc = (ViewControllerB *)[sb instantiateViewControllerWithIdentifier:@"CountrySelection"];
    vc.modalTransitionStyle = UINavigationControllerOperationPop;
    vc. myDelegate = self;
    [self presentViewController:vc animated:YES completion:NULL];
}