【发布时间】:2016-05-26 09:20:07
【问题描述】:
我是 iOS 编程新手,我敢肯定很多其他人都遇到过同样的问题。
问题是,我使用 AFNetworking 来处理我的 http 请求。
我正在尝试在我的 init 方法中获取一些数据,我想用 ViewDidLoad() 中的这些数据分配一个变量。
似乎AFNetworking 发送带有块的get 请求**(可能是异步的,但我还没有了解线程)**。
当我分配时,我试图获取的数据还没有返回。
我搜索过类似的答案
The execution of block is always delayed
block execution iOS and assigning variable
Variable returning null after block execution
但没有找到解决办法。
不知道是不是多线程机制的原因,请问如何解决?
代码
HomeController.m
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSInteger cateid = indexPath.row + 1;
HomeTabCategoryController* categoryController = [[HomeTabCategoryController alloc] initWithCategoryId:cateid andCategoryName:[_categories objectForKey: [@(indexPath.row + 1) stringValue]]];
[self.navigationController pushViewController:categoryController animated:YES];
}
CategoryController.m
-(instancetype)initWithCategoryId:(NSInteger)categoryId andCategoryName:(NSString*)categoryName{
self = [super init];
if (!self) {
return nil;
}
[ProductModel getProductsIdOfCategory:_categoryId success:^(BOOL result, NSString* message, NSArray* productIds){
if (!result) {
_productIds = productIds;
}else{
[self toast:message];
}
}failure:^(NSError* error){
NSLog(@"%@", error);
}];
return self;
}
-(void)viewDidLoad{
NSLog(@"loading view");
[super viewDidLoad];
self.title = _categoryName;
[self getData];
}
- (void)getData{
for (NSNumber* proId in _productIds) {
[ProductModel getProductWithId:[proId integerValue] success:^(BOOL result, NSString* message, ProductEntity* product){
if (!result) {
[_products addObject:product];
}else{
[self toast:message];
}
}failure:^(NSError* error){
NSLog(@"%@", error);
}];
}
}
当getData被执行时,_productIds仍然是nil(我在success块中赋值)。
【问题讨论】:
-
你能分享更多细节吗?为什么需要调用 INIT ?我相信这可以通过 GCD 串行队列来实现。
-
这是因为我在
HomeController中有一个UITableView,当我选择某一行时,我想显示一个新视图。实际上我以前从未了解过GCD。如果是GCD的问题,我一定会自己去拿一些文档并学习使用它。但问题是,我什至不知道问题到底是什么(我的意思是我想要更多关于事情在我的代码中是如何工作的细节)。你能给点建议吗?块中是否创建了线程?该块何时实际执行?预先感谢。 :)
标签: ios objective-c multithreading afnetworking block