[英]ios Objective C delegate methods
这是我对目标C的第一天,对于缺乏知识我深表歉意。
我需要将现有的SKD导入到应用程序中,并成功完成。 现在,我需要创建委托方法,但我不知道该怎么做。
这是SDK(SDKManager.h)中包含的头文件的结构:
@protocol SDKManagerDelegate;
@interface SDKManager : NSObject
@property (nonatomic, weak) id<SDKDelegate> delegate;
+(void)initialize:(NSString*)appId withKEY:(NSString*)key;
+(void)setHandler:(id)delegate;
@end
@protocol SDKManagerDelegate <NSObject>
@required
-(void)appDidReceiveTokens:(NSDictionary*)items withResponse:(NSDictionary*)response;
@end
因此,我可以从FirstViewController.m导入标头并调用两个方法:
#import "FirstViewController.h"
#import "SDKManager.h"
@interface FirstViewController ()
@end
@implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[SDKManager setHandler:[UIApplication sharedApplication].delegate];
[SDKManager initialize:@"AppId"withKEY:@"1234"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
但是我注意到我无法调用其他方法(即appDidReceiveTokens)。 实际上,说明需要创建这些方法,但我不知道在哪里。
任何帮助都非常感谢。 谢谢
您不会在实现委托方法的文件中直接调用委托方法。 查看有关授权概念的Apple文档 。
为了正确实现此目的,您可以在类中采用委托,然后实现@required
和/或@optional
的委托方法。
您已经正确创建了委托协议和一个属性来存储SDKManager
的委托。
您的setHandler:
和initialize:withKEY:
方法是类方法,而delegate
属性属于SDKManager
每个实例 。 在没有看到SDKManager
实现文件(.m)的SDKManager
,很难知道为什么用这种方法进行设置。 您可能正在尝试遵循单例模式-如果是这样,请继续阅读它,例如此处 。
这样做的原因是您拥有设置调用setHandler方法的类方法,并且委托是属性,因此您在哪里分配委托以及何时以及如何调用委托。 我希望您了解什么是类和实例。 因此,在创建对象实例之前,您无法调用委托。
您有两种不同的类方法,用于为类设置一些属性,将它们作为属性有意义。
更通用,更好的方法是这样的,
@protocol SDKManagerDelegate <NSObject>
@required
-(void)appDidReceiveTokens:(NSDictionary*)items
withResponse:(NSDictionary*)response;
@end
@protocol SDKManagerDelegate;
@interface SDKManager : NSObject
- (instancetype)initWithAppId:(NSString *)appId
key:(NSString *)key
delegate:(id<SDKManagerDelegate>)delegate;
@end
@interface SDKManager ()
@property (nonatomic, copy, readonly) NSString *appId;
@property (nonatomic, copy, readonly) NSString *key;
@property (nonatomic, weak, readonly) id<SDKManagerDelegate> delegate;
@end
@implementation SDKManager
- (instancetype)initWithAppId:(NSString *)appId
key:(NSString *)key
delegate:(id<SDKManagerDelegate>)delegate
{
if (self = [super init]) {
_appId = [appId copy];
_key = [key copy];
_delegate = delegate;
}
return self;
}
- (void)doSomeNetworkRequestHere
{
[self fetchTokenFromServer:^(NSDictionary *tokens, NSDictionary *response){
[self.delegate appDidReceiveTokens:tokens
withResponse:response];
}];
}
- (void)fetchTokenFromServer:(void(^)(NSDictionary *tokens, NSDictionary *response))completion
{
}
@end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.