2017-07-04 37 views
0

我想從完成塊發送回調監聽器。我啓動自定義回調UIView &完成塊從父視圖控制器執行(其中UIView子查看)。下面是代碼...(我不想使用代理)在ViewController.mObjective-C回撥沒有與不幸的背景崩潰工作

-(void) exportCompletionBlock:(ExportCompletion)callback 
{ 
    if (callback) { 
     self.exportBlock = callback; 
    } 
} 

實施

的回撥宣言ViewController.h

typedef void(^ExportCompletion)(BOOL success, NSURL* url); 
@property (nonatomic, copy) ExportCompletion exportBlock; 
-(void) exportCompletionBlock:(ExportCompletion)callback; 

初始化&的回撥實施(致電)

-(void)blockAlertAppear:(float)progress{ 
    if(EXPORT_SESSION_COMPLETED!=progress) 
     doing something... 
    if(EXPORT_SESSION_COMPLETED==progress){ 
     self.exportBlock(YES, mCompositor.url); 
    } 
} 

呼叫在uicustomview回操作... CustomUIView.m

-(void) initUIView{ 
    [(ViewController*)[[self superview] nextResponder] exportCompletionBlock:^(BOOL success, NSURL *url) { 
    if (success) { 
     doing something... 
    } 
}]; 

我可以在這裏使用委託,但我想用回電話。回電後我很新。我想知道爲什麼我有崩潰(它來自後臺 - 所以沒有理由)&我該如何優化代碼?

回答

2

如果[(ViewController*)[[self superview] nextResponder]返回零可能是崩潰的原因。但是使用[[self superview] nextResponder]並不是一個好習慣。讓我們嘗試一個完成處理程序。我試圖給你一個例子。

ViewController.h

typedef void(^ExportCompletion)(BOOL success, NSURL* url); 
@property (nonatomic, copy) ExportCompletion exportBlock; 

的回撥宣言在您的視圖 - 控制ViewController.m無需分配exportCompletionBlock。只需在需要時分配。舉個例子,你在你的CustomView中有一個委託,它在ViewController.m中實現。

在你CustomUIView.h從你期望的事件像

添加此

typedef void(^ExportCompletion)(BOOL success, NSURL* url); 

@protocol CustomUIViewDelegate <NSObject> 
- (void) startExport:(ExportCompletion)completionBlock; 
@end 

打電話給你的委託在你CustomUIView.m

- (IBAction)ButtonTapped:(UIButton *)sender { 
    [self.delegate startExport:^(BOOL success, NSURL *url) { 
     if (success) { 
      doing something... 
     } 
    }]; 
} 

在你ViewCOntroller.m代碼保持不變,但有一個幻燈片修改一一點點

一樣了

-(void)blockAlertAppear:(float)progress{ 
    if(EXPORT_SESSION_COMPLETED!=progress) 
     doing something... 
    if(EXPORT_SESSION_COMPLETED==progress){ 
     self.exportBlock(YES, mCompositor.url); 
    } 
} 

ViewCOntroller.m

- (void) startExport:(ExportCompletion)completionBlock{ 
    self.exportBlock = completionBlock; 
    the thing you want to do... 
} 

這實現委託的處理完成塊的方式。我不知道它會對你有多大幫助。這只是一種實現代碼的新方法。 &它可以幫助您防止使用[[self superview] nextResponder]視圖依賴性。

1

爲什麼最後一個方法調用「initUIView」?如果你在沒有添加到超級視圖([viewController.view addsubview:yourView])之前初始化新視圖,視圖沒有超級視圖。我想,如果你在NSLog中打印[(ViewController *)[[self superview] nextResponder],你會看到Nil。這是崩潰的原因