gpt4 book ai didi

ios - Objective C 对特定事件的回调

转载 作者:行者123 更新时间:2023-11-29 10:34:13 25 4
gpt4 key购买 nike

我是 Objective-C 的新手,正在尝试开发自己的回调函数,回调函数在特定事件上被调用,比如从网络接收数据,就像 NSURLprotocol 所做的那样,一旦接收到它就会 NSLog 消息“事件已发生”或在 UIViewController 或任何 UI 相关操作上显示为文本。

所以,我完全不知道应该在哪里调用 eventOccuredMethod 来让 receiveController 被调用并执行其中的实现。

我以前使用过像 NSURLProtocol 这样的协议(protocol),但我不知道如何实现它们来调用这样的回调。

欢迎任何视频链接、答案、文章链接。

//Sample.h file 
#import <Foundation/Foundation.h>
@class Sample;
@protocol SampleProtocol <NSObject>
-(void)receivedCallback;
@end

@interface Sample : NSObject
@property (nonatomic,weak) id<SampleProtocol> delegate;
-(void)eventOccured;
@end

//示例.m文件

#import "Sample.h"

@implementation Sample
-(void)eventOccured{
if([_delegate conformsToProtocol:@protocol(SampleProtocol)])
[_delegate receivedCallback];
}
@end

//ViewController.h文件

@interface ViewController : UIViewController<SampleProtocol>

@end

//ViewController.m文件

#import "ViewController.h"

@interface ViewController (){

Sample *s;
}

@end

@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
s = [[Sample alloc] init];
s.delegate = self;
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

-(void)receivedCallback:(Sample *)sample{
NSLog(@"Event Has Occured");
}

@end

我不确定我正在打的以下电话......

- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
Sample *s = [[Sample alloc] init];
[s eventOccured];
}

最佳答案

您正在以正确的方式实现委托(delegate)模式。但是,如果 Sample 对象不生成自己的事件,而是中继从其他地方发布给它的事件,就像您的示例中的情况一样,您必须确保具有 ViewController作为委托(delegate)和接收消息的对象其实是一样的。一种方法是使 Sample 成为单例:

#import "Sample.h"

@implementation Sample

+ (instancetype)sharedInstance
{
static id sharedInstance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[[self class] alloc] init];
});
return sharedInstance;
}

-(void)eventOccured{
if([_delegate conformsToProtocol:@protocol(SampleProtocol)])
[_delegate receivedCallback];
}

@end

然后在你的 View Controller 中你会做

s = [Sample sharedInstance];

在你的 appDelegate 中:

[[Sample sharedInstance] eventOccured];

正如 vikingosegundo 指出的那样,另一种确保您使用相同对象的方法是从 appDelegate 设置 View Controller 的 Sample 对象。

对于此用例,您还可以考虑使用通知。

关于ios - Objective C 对特定事件的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27939731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com