[英]Calling block on a nil object gives exc_bad_access
我遇到了這種情況,當我在nil對象上調用一個塊時,我的應用程序因exec_bad_access而崩潰。 我可以通過添加if條件來解決此問題,但我想知道為什么在nil對象上調用block會導致bad_access?
@interface CustomView :UIView
@property (nonatomic, strong) UIImage* sourceImage;
@property (nonatomic, copy) void(^doneSwipingBlock)();
- (void)testMethod;
@end
//Another Class
//Sample Code (this is not the actual code but shows the crash
CustomView view = nil;
view.sourceImage = [UIImage imageNamed:@"image.png"]; //no error as view is nil
[view testMethod]; //no error as view is nil
view.doneSwipingBlock(); //Crashes here
/*
//This works fine
if (view.doneSwipingBlock) {
view.doneSwipingBlock();
}
*/
因為雖然塊是對象,所以不應將對塊的操作視為尊重Objective-C語義。 就像從NULL讀取會導致錯誤的訪問一樣,調用NULL塊也會導致錯誤的訪問。 這與函數指針的行為一致(調用NULL函數指針會使您的程序崩潰),並且由於C和C ++中都提供了塊,因此使用此行為比純粹的Objective-C行為更有意義。
不會通過objc_msgSend
調用invoke方法,該方法處理並取消對Objective-C對象上的nil對象的調用。
塊是變量,不是方法。 您可以從block屬性中獲得與從int
屬性中獲得的相同的期望。 它們就像您有一個名為Block
類,上面有一個invoke
方法,您每次需要它做一些不同的事情時都將它子類化,只是編譯器會完成所有子類化部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.