这是您在问题中指定的类似方法,用 objc 编写:假设我们有一个类 Client 和 FeedEvents。客户端类被实现来处理网络连接(例如使用AFNetworking)。FeedEvents 与 Client 类互连以处理来自网络的事件,但此事件必须调用“客户端”代码块以使事情变得更简单。
@interface Client : NSObject
- (void)connect;
@end
typedef void (^EventBlock) (id someData);
@interface FeedEvents : NSObject
@property (nonatomic, strong) EventBlock eventBlock;
@end
@interface ProgramClass : NSObject
- (void)fetchEvents;
@end
@implementation ProgramClass
- (void)fetchEvents {
// I prefer using singleton for generic instances that are used through entire application
// in the same way, but also sometimes it's better to use this approach:
// ...
Client *connectionClient = [Client new]; // or custom -[+[ alloc] initWithParameters...];
FeedEvents *eventListener = [FeedEvents new]; // or custom -[+[ alloc] initWithParameters...];
eventListener.eventBlock = ^(id someData) {
// do some additional configuration
};
// using background queue to connect to some host
// but this is only for purpose of the method translation, because
// AFNetworking provides very reach background API
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, kNilOptions), ^{
[connectionClient connect];
};
}
@end
您还可以将 NSOperation 子类化以使用此 - (void)main {} 方法,如您的示例中一样,并在后台线程中完全运行它。
在这个示例代码中,您应该知道块参数等存在一些内存管理问题。在这种情况下,对您来说更简单的方法是继承 NSOperation 并像这里一样在后台运行它。
希望这会有所帮助