我正在尝试使用GCD更新我的自定义标签,但我得到的是我用以下内容初始化标签的文字:
-(void)drawCardInfo{
__block NSString *cardString;
PPLinearLayoutLabelItem *cardDetails = [[PPLinearLayoutLabelItem alloc] initWithText:@"CREDIT CARD INFO" font:[PPFonts regular18] maxWidth:[LayoutValues getMaxWidthClipped]];
[cardDetails setPaddingTop:20];
[cardDetails setPaddingBottom:10];
[self.topContainerContent addObject:cardDetails];
PPLinearLayoutLabelItem *cardInfo = [[PPLinearLayoutLabelItem alloc] initWithText:@"Data" font:[PPFonts bold16] maxWidth:[LayoutValues getMaxWidthClipped]];
[cardInfo setPaddingTop:0];
[self.topContainerContent addObject:cardInfo];
LinearLayoutHorizontalLine *line1 = [[LinearLayoutHorizontalLine alloc] initWithMaxWidth:[LayoutValues getMaxWidthClipped]];
[self.topContainerContent addObject:line1];
dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSOperationQueue *networkQueue = [[NSOperationQueue alloc] init];
networkQueue.maxConcurrentOperationCount = 5;
NSURL *url = [NSURL URLWithString:@"https://xxxxxxxxxxxxxxxxxx"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
if([string isEqualToString:@""]){
} else {
NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
NSString *cardType = [dict objectForKey:@"credit_card_type"];
NSString *cardFinalFour = [dict objectForKey:@"credit_card_last_4"];
cardString = [NSString stringWithFormat:@"%@ **** %@",cardType, cardFinalFour];
NSLog(@"%@",cardString);
}
dispatch_async(dispatch_get_main_queue(), ^{ [cardInfo setText:cardString]; });
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%s: AFHTTPRequestOperation error: %@", __FUNCTION__, error);
}];
[networkQueue addOperation:operation];
});
}
我成功注销了证明网络调用在单独线程上运行正常的值。我的标签还没有更新。我该如何缓解这种情况?
答案 0 :(得分:0)
看起来您正在尝试在后台线程中更新标签的文本。在主线程以外的任何地方更新UI元素并不是一个好主意,因为您永远不知道异步作业何时完成。
您可以使用以下方式进行操作:
获取主线程,然后更新文本标签
Sub
使用it("calls the totalBogof() function", function() {
spyOn(basket, "totalBogof");
basket.total();
expect(basket.totalBogof).toHaveBeenCalled();
});
将dispatch_async(dispatch_get_main_queue(), ^{
//Code here to which needs to update the UI in the UI thread goes here
});
与依赖关系一起使用(这将是最长的)