0

I create my Custom Container View Controller according to Apple’s guide, which means I use no segue. To send data from my ChildVC to my ParentVC I use the following schema.

In ChildVC.h

typedef void (^ActionBlock)(NSUInteger);

@property (nonatomic, copy) ActionBlock passIndexToParent;

Then in ParentVC.m viewDidLoad

childVC.passIndexToParent=^(NSUInteger imageIndex){
//do some cool stuff
}

ChildVC contains a TableView and the button(s) to be clicked is in a cell in the table so I use the following technique to get the index of the row clicked

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //…

     //target action
    [cell.myImageButton addTarget:self action:@selector(getIndexOfTapped:) forControlEvents:UIControlEventTouchUpInside];
    //…
    return cell;
}


- (void) getIndexOfTapped:(id)sender
{
    NSLog(@“X image tap confirmed");
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    if (indexPath != nil)
    {

        NSLog(@"INDEX of X image tapped is %ld",(long)indexPath.row);
        self.passIndexToParent(indexPath.row);//Thread 1: EXC_BAD_ACCESS(code=1, address=0X10)
    }
}

Now when I run the program I get

Thread 1: EXC_BAD_ACCESS(code=1, address=0X10)

for line

self.passIndexToParent(indexPath.row);

No further error data. Any help fixing this problem?

4

1 回答 1

0

我强烈建议不要使用这种模式。主要是因为创建保留周期太容易了。如果您传递给子级的块包含对父级的强引用,那么您将无法中断保留周期,除非您在解除父级时手动取消子级块。

相反,您应该在孩子上创建一个委托协议。它看起来像这样:

//ChildVC.h

@class ChildVC

@protocol ChildVCDelegate <NSObject>

-(void)childVC:(ChildVC *)childVC didSelectIndex:(NSUInteger)index;

@end

@interface ChildVC

...

@property (nonatomic, weak) id<ChildVCDelegate> delegate;

...

@end

//ChildVC.m

if (indexPath != nil)
{
    if ([self.delegate respondsToSelector:@selector(childVC:didSelectIndex:)]) {
        [self.delegate childVC:self didSelectIndex:indexPath];
    }
}

然后定义 -(void)childVC:(ChildVC *)childVC didSelectIndex:(NSUInteger)index; 方法并确保将父级设置为子级的委托。

另请参阅:关于 iOS 常见问题的 #1 问题

但是,叹息,为了回答您的问题,您有时会在尚未设置该块时调用它。在调用块之前,您需要进行 nil 检查。

于 2014-08-13T01:23:12.117 回答