2012-06-19 36 views
13

所以,我想傳遞一個塊作爲NSAlertcontextInfo參數。如何投放塊和無效*

[myAlert beginSheetModalForWindow: theWindow 
        modalDelegate: myAlert 
        didEndSelector: @selector(alertDidEnd:returnCode:contextInfo:) 
         contextInfo: (void *) aBlock]; 

,並把它找回來的另一端:

void (^responseBlock)() = (__bridge_transfer void (^)()) contextInfo; 

其中,工程的程度。我呼籲beginSheetModalForWindow:... ABLOCK之前在0x00007fff610e1ec0,並在響應(alertDidEnd:...),contextInfo是0x00007fff610e1ec0

然而,當我嘗試調用該塊:

responseBlock(); 

我收到以下錯誤

error: called object type '__block_literal_generic *' is not a function or function pointer
error: 1 errors parsing expression

一個人如何正確地投塊到從void * S表示簡單轉移的緣故?

編輯: 全部試圖代碼,使用的答案建議投的方法。我現在收到關於responseBlock();調用一個EXC_BAD_ACCESS錯誤。

- (void)alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo 
{ 
    void (^responseBlock)() = (__bridge typeof(responseBlock)) contextInfo; 

    switch (returnCode) 
    { 
     case NSCancelButton: 
     { 
      break; 
     } 

     case NSOKButton: 
     { 
      responseBlock(); 
      break; 
     } 
    } 
} 

其他註釋: 當使用__bridge,的responseBlock存儲器地址和contextInfo是不同的,而用__bridge_transfer,它們是相同的。既不緩解EXC_BAD_ACCESS問題。

工作:

[myAlert beginSheetModalForWindow: theWindow 
        modalDelegate: myAlert 
        didEndSelector: @selector(alertDidEnd:returnCode:contextInfo:) 
         contextInfo: (__bridge_retained void *) [aBlock copy]]; 

後來......

void (^responseBlock)() = (__bridge_transfer typeof(responseBlock)) contextInfo; 
+0

我有一個答案,但我無法重現你的問題。我想知道爲什麼這是...你有任何額外的警告/編譯標誌? –

回答

6

這裏有一個小例子。我覺得你的代碼的問題是,你要使用__bridge_transfervoid *這是不是內存ARC管理:

void takesBlock(void *asPointer) 
{ 
    void (^asBlock)() = (__bridge typeof asBlock) asPointer; 

    asBlock(); 
} 

int main() 
{ 
    @autoreleasepool { 
     takesBlock((__bridge void *)[^{ 
      NSLog(@"Hello World!"); 
     } copy]); 
    } 
} 
+0

'空隙(^ responseBlock)()=(__bridge typeof運算responseBlock)contextInfo;'給我的語法錯誤:'預期 ')'''上在responseBlock''typeof運算responseBlock'。思考? –

+0

@pcperini你可以張貼函數的內容成糊狀倉? –

+0

增加了問題的全部功能。錯誤已從類型錯誤更改爲完整的EXC_BAD_ACCESS。 –