在一个有返回值的方法中,用block回传的解决方法

在项目中,集成了环信sdk,当使用

- (id<IConversationModel>)conversationListViewController:(EaseConversationListViewController *)conversationListViewController modelForConversation:(EMConversation *)conversation;

 

这个方法时候,发现,返回的是一个model,而我在拼接model时候,需要进行查询操作,查询操作在block中,如下:

        [[DataBaseHandle shareDataBaseHandle] selectOneTabelName:@"contactList"

                                                             cls: MUCContactListModel.class

                                                             key:@"huanxinId" value:conversation.conversationId

                                                          result:

         ^(NSArray *resultArray) {

            listModel = resultArray.firstObject;

        } error:^(NSError *error) {

            mError = error;

        }];

 

问题再此出现了:需要的model在block中,不知道什么时候执行完成,而这个方法又要返回该model,该如何处理呢?

最后,问题如下解决了:

 

- (id<IConversationModel>)conversationListViewController:(EaseConversationListViewController *)conversationListViewController modelForConversation:(EMConversation *)conversation  {

    EaseConversationModel *model = [[EaseConversationModel alloc] initWithConversation:conversation];  

    if (model.conversation.type == EMConversationTypeChat) {

#warning !!!replaceFMDBByFMDBQueue---

        __block MUCContactListModel *listModel = nil;

        __block NSError *mError = nil;

        

        [[DataBaseHandle shareDataBaseHandle] selectOneTabelName:@"contactList"

                                                             cls: MUCContactListModel.class

                                                             key:@"huanxinId" value:conversation.conversationId

                                                          result:

         ^(NSArray *resultArray) {

            listModel = resultArray.firstObject;

        } error:^(NSError *error) {

            mError = error;

        }];

        do {

            usleep(500);

        } while (!listModel || !mError);

        

        if (mError) {

            DLog(@"%@",mError.description);

            return model;

        }

        

        model.title = listModel.name;

        model.avatarURLPath = listModel.photo;

        model.avatarImage = nil;

  

    }

    return model;

}

 

即:在block代码块后面,进行一个循环判断,只有当出现error,或者有model的时候,再向下执行,否则就持续休眠500毫秒。

posted on 2017-03-01 10:33  晨趣  阅读(2528)  评论(0编辑  收藏  举报