我不確定您在「主叫方消失時」中的「主叫方」是什麼意思。儘管如此,您可以從任何地方訪問應用程序委託。
[UIApplication sharedApplication].delegate;
如果您需要調用對您的特定應用程序委託唯一的方法,則需要導入它並進行強制轉換。
#import "MyAppDelegate.h"
// ...
MyAppDelegate *appDelegate = (MyAppDelegate *)[UIApplication sharedApplication].delegate;
更新:
要調用自己的庫方法上的任何應用程序委託,使用的協議。
// The app delegate in your library users app
#import "YourFancyLibrary.h"
@interface MyAppDelegate : NSObject <UIApplicationDelegate, YourFancyLibraryDelegate>
// In YourFancyLibrary.h, declare that protocol
@protocol YourFancyLibraryDelegate
- (void)myFancyMethod;
@end
// Refer to it in the guts of your library.
id<YourFancyLibraryDelegate> delegate = [UIApplication sharedApplication].delegate;
if (![delegate conformsToProtocol:@protocol(YourFancyLibraryDelegate)]) return;
if (![delegate respondsToSelector:@selector(myFancyMethod)]) return;
[delegate myFancyMethod];
這會讓你指定什麼方法您的圖書館用戶需要實現你的API清晰,是一個很好的解決方案,因爲它允許編譯時檢查,而不是依賴於運行時動態消息發送。
您也可以跳過該協議,並直接調用它的方法。
id appDelegate = [UIApplication sharedApplication].delegate;
SEL methodToCall = @selector(someMethod);
if ([appDelegate respondsToSelector:methodToCall]) {
[appDelegate performSelector:methodToCall];
}
是的,我想調用應用程序委託的自定義方法。由於我的類是通用的,可以包含在不同的項目中,因此該類不知道用於包含在其中的項目中的Application委託類的名稱。是否有方法可以編寫第二個調用,而不需要剔除類應用程序委託的名稱。 – Oliver
正確的做法是要求您的庫的用戶在他們的應用程序委託中實現協議。我會更新我的答案。 –
我同意,但我不能強制應用程序實現一個方法,這個方法只會在某些特定情況下被調用,當一個特定的調用觸發到通用對象上時會發生這種情況。對於泛型類中實現的所有其他方法,這是無用的。所以我寧願檢查應用程序委託是否實現了該方法,如果不是,則轉到第三條路線。 – Oliver