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

时间:2017-02-02 14:27:42

标签: objective-c listener objective-c-blocks completion-block

是否无法获得完成块成功,然后从另一种方法获得数据?

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

2 个答案:

答案 0 :(得分:0)

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

没关系,但考虑一些事情:(1)复制块......

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

(1.5)该块将更好地命名&#34; successHandler&#34;或类似的东西,并且该属性可以公开,因此您可以删除createOrderWithsuccess: setter。

(2)由于您不确定调用者是否设置了阻止,请在调用之前检查nil(否则会发生崩溃)

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

(3)在你完成之后没有块。如果块引用此对象,则对其进行修改将中断保留周期。

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

答案 1 :(得分: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:的类都知道它。