开发者

iPhone - Referencing the application delegate within a generic class

I a writing a generic class that may be used in different projects by link.

At some moment, I call a method on a listener given by the one that owns the object and kept by assign into the class.

But sometimes, that caller may disapear, so I want in that case to route the return message to the application delegate.

Here is how I do for the caller (the caller is the one that created and owns the instance of my class) :

if ([self.responseListener respondsToSelector:@selector(serverAnswered:error:)]) {
        // some job to construct the return object

        [self.responseListener performSelector:@selector(serverAnswered:error:) withObject:response withObject:nil];
    }

How may I reference the app delegate class in place of responseListener when the caller has disapeared开发者_StackOverflow中文版 ?


I'm not sure what you mean with "caller" in "when the caller has disappeared". Here's how you can access the application delegate from anywhere, though.

[UIApplication sharedApplication].delegate;

If you need to call methods on it unique to your particular application's delegate, you need to import it and cast.

#import "MyAppDelegate.h"

// ...

MyAppDelegate *appDelegate = (MyAppDelegate *)[UIApplication sharedApplication].delegate;

Update:

To call your own library methods on any app delegate, use a protocol.

// 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];

This will make your API clear as you specify what methods your library users need to implement, and is a good solution as it allows for compile time checks instead of relying on run time dynamic message sending.

You can also skip the protocol, and call methods on it directly.

id appDelegate = [UIApplication sharedApplication].delegate;
SEL methodToCall = @selector(someMethod);
if ([appDelegate respondsToSelector:methodToCall]) {
    [appDelegate performSelector:methodToCall];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜