以前一直在非64位機器下測試一切正常的程序,在iPhone5s下平白無故崩潰。崩潰的位置是調用objc_msgSend時出現。通過一番辛苦搜索終於發現蘋果官網上有一段這樣的描述:html
Dispatch Objective-C Messages Using the Method Function’s Prototypeios
An exception to the casting rule described above is when you are calling the objc_msgSend
function or any other similar functions in the Objective-C runtime that send messages. Although the prototype for the message functions has a variadic form, the method function that is called by the Objective-C runtime does not share the same prototype. The Objective-C runtime directly dispatches to the function that implements the method, so the calling conventions are mismatched, as described previously. Therefore you must cast the objc_msgSend
function to a prototype that matches the method function being called.架構
Listing 2-14 shows the proper form for dispatching a message to an object using the low-level message functions. In this example, thedoSomething:
method takes a single parameter and does not have a variadic form. It casts the objc_msgSend
function using the prototype of the method function. Note that a method function always takes an id
variable and a selector as its first two parameters. After the objc_msgSend
function is cast to a function pointer, the call is dispatched through that same function pointer.app
Listing 2-14 Using a cast to call the Objective-C message sending functionside
- (int) doSomething:(int) x { ... } - (void) doSomethingElse { int (*action)(id, SEL, int) = (int (*)(id, SEL, int)) objc_msgSend; action(self, @selector(doSomething:), 0); }
貌似是說不能直接使用objc_msgSend的原型方法來匿名調用,不然會出現異常。結果嘗試了上面的方法強制轉換成必定的方法後,再次運行沒有崩潰了,Luck!!測試
補充說明(2015-8-5):this
對於返回結構體的方法,若是使用objc_msgSend進行調用是會拋出異常EXC_BAD_ACCESS:spa
CGSize (*action)(id, SEL, int) = (CGSize (*)(id, SEL, int)) objc_msgSend; CGSize size = action(self, @selector(doSomething:), 0);
這樣的作法是有可能會出現崩潰問題的(可是不必定每一個程序都必然會出現),通過查看官方文檔發現,objc_msgSend有一個擴展版本objc_msgSend_stret,是專門用於處理返回結構體的狀況,所以把代碼改成以下所示便可解決問題:prototype
CGSize (*action)(id, SEL, int) = (CGSize (*)(id, SEL, int)) objc_msgSend_stret; CGSize size = action(self, @selector(doSomething:), 0);
注:此調整隻有在armv7架構下須要進行調整,若是包含arm64則不須要。