0

是否不可能获得完成块成功然后从另一种方法接收数据?

@property myCompletion;

// I have first call listeners, i can't add this in to "createOrderWithsuccess"

-(void)listeners {
    [[SocketIOManager sharedInstance].socket on:@"someAction" callback:^(NSArray* data, SocketAckEmitter* ack) {
        // data received
        myCompletion(data);

    }];

}

// this will be called <del>first</del> later
- (void)createOrderWithsuccess:^(NSArray *data) {
    // but it has to wait then data will be received  
    myCompletion = success;
 }
4

2 回答 2

0

如果我正确理解你的意图,这个想法很好。调用者可以将该createOrderWithsuccess:方法用作完成块的设置器。随后,调用者调用listeners他们之前设置的块将在成功时调用。

没关系,但请考虑以下几点:(1)复制块......

@property (nonatomic, copy) void (^myCompletion)(NSArray *);

(1.5) 该块最好命名为“successHandler”或类似的名称,并且该属性可以公开,因此您可以删除createOrderWithsuccess:setter。

(2) 由于您不确定调用者是否设置了块,因此在调用之前检查 nil (否则会崩溃)

if (self.myCompletion) self.myCompletion(data);

(3)在你完成后将块归零。如果块引用了这个对象,nil 将打破保留循环。

if (self.myCompletion) self.myCompletion(data);
self.myCompletion = nil;
于 2017-02-02T15:07:22.340 回答
0

有点难以理解您在寻找什么,但这可能就是它。这就是我在我的应用程序中处理完成回调的方式:

@import Foundation;

typedef void (^CompletionBlock)(NSArray *data);

@interface TheClass()

@property (nonatomic, copy) CompletionBlock *myCompletion;

@end

@implementation TheClass()

// ....


- (void) createOrderWithsuccess:(CompletionBlock)success {
    _myCompletion = success;
}

-(void)listeners {
    [[SocketIOManager sharedInstance].socket on:@"someAction" callback:^(NSArray* data, SocketAckEmitter* ack) {
        // data received
        _myCompletion(data);

    }];
}

// Alternatively, breaking possible retain cycles
-(void)listeners {
    __weak TheClass *weakSelf = self;
    [[SocketIOManager sharedInstance].socket on:@"someAction" callback:^(NSArray* data, SocketAckEmitter* ack) {
        // data received
        if(weakSelf.myCompletion) weakSelf.myCompletion(data);
    }];
}

应该在typedef.h 文件中,以便此类和调用者都createOrderWithsuccess:知道它。

于 2017-02-03T07:35:23.367 回答