如何从 objective-c 中的另一个方法执行完成块?

how to execute completion block from another method in objective-c?

是否无法获得完成块成功然后从其他方法接收数据?

@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;
 }

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

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

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

(1.5) 该块最好命名为 "successHandler" 或类似名称,并且 属性 可以设为 public,因此您可以删除 createOrderWithsuccess: setter.

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

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

(3) 完成后将块归零。如果块引用此对象,nil-ing 它将打破保留周期。

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

有点难以理解您要查找的内容,但可能就是这样。这是我在我的应用程序中处理完成回调的方式:

@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 文件中,这样 class 和调用 createOrderWithsuccess: 的人都知道它。