簡體   English   中英

Objective-C try-catch - 為什么編譯? 為什么返回不同的構建調試與發布?

[英]Objective-C try-catch - why does this compile? And why is the return different building debug vs release?

在Objective-C類別中找到了這個有趣的代碼,用於捕獲NSExceptions並將它們作為NSErrors傳遞給Swift代碼。

我不明白的是:1)為什么甚至編譯? 如果拋出異常,則永遠不會有返回值。 2)為什么在使用debug(優化級別none)和release(優化級別最小/最快)進行編譯時返回值會有所不同?

- (BOOL)catchException:(void(^)())tryBlock error:(__autoreleasing NSError **)error {
   @try {
       tryBlock();
       return YES;
   }
   @catch (NSException *exception) {
       NSMutableDictionary *userInfo = [exception.userInfo mutableCopy];
       if (!userInfo) userInfo = [NSMutableDictionary new];
       userInfo[NSLocalizedDescriptionKey] = exception.reason;
       *error = [[NSError alloc] initWithDomain:exception.name code:0 userInfo:userInfo];
   }
   // Note the missing return value outside the try-catch
 }

調用函數:

NSError *error;
BOOL result = [self catchException:^{
    @throw [NSException exceptionWithName:@"Exception" reason:@"WTF?" userInfo:nil];
} error:&error];

NSLog(@"Result: %@", result ? @"YES" : @"NO");

在使用Debug方案進行編譯和運行時,我們得到:

2017-02-09 10:01:39.695 Compile Test[23129:630118] Result: NO

在使用Release方案時也是如此:

2017-02-09 10:01:39.695 Compile Test[23129:630118] Result: YES

因此,在這兩種情況下都會出現返回值,即使try-catch塊之外沒有返回值,也永遠不會達到try-catch中的返回值。 我們都在這里很困惑?!

這是編譯器錯誤或“檢查控制流以確保返回值存在”選項被關閉(如果有)。

不同的返回值是因為行為未定義。

基本上,無論發生在插槽中的什么 - 可能是寄存器,可能在堆棧上,取決於目標CPU的ABI - 在函數返回時保存返回值將被使用。

如果沒有優化,編譯器將不會重用寄存器和堆棧; 每個變量都有自己的空間,並保存到函數的末尾。 通過優化,編譯器將主動重用內存,從而導致行為更改。 這也是調試優化代碼如此痛苦的原因; 'p myVariable'可能會打印出意想不到的東西,因為'myVariable'已被回收。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM