iOS 异步请求网络数据,传值问题

记录学习中遇到的问题


出问题的写法,定义方法请求网络数据,直接在调用方法的页面用数组接收返回的数组。偶尔会出现程序崩溃情况


-(NSMutableArray *)requestAllDataWithListId:(NSString *)listId{
    NSMutableArray *resultArray = [NSMutableArray array];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *urlStr = [NSString stringWithFormat:kLOLMoviesWithAuthor, listId];
    [manager GET:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *html = operation.responseString;
        NSData* data=[html dataUsingEncoding:NSUTF8StringEncoding];
        id dict=[NSJSONSerialization  JSONObjectWithData:data options:0 error:nil];
        NSArray *array = dict[@"videos"];
        for (NSDictionary *dic in array) {
            LOLSomeOneProgramListModel *model = [[LOLSomeOneProgramListModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [resultArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            self.result();
        });
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    return resultArray;
    
}

导致程序崩溃的原因是,上面返回的数组是在block体中数据不确定有没有请求下来的情况下执行的,

正确写法,在请求完数据后通过block体回调把要返回的值作为参数传出去

-(void) requestAllDataWithListId:(NSString *)listId{
    NSMutableArray *resultArray = [NSMutableArray array];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *urlStr = [NSString stringWithFormat:kLOLMoviesWithAuthor, listId];
    [manager GET:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *html = operation.responseString;
        NSData* data=[html dataUsingEncoding:NSUTF8StringEncoding];
        id dict=[NSJSONSerialization  JSONObjectWithData:data options:0 error:nil];
        NSArray *array = dict[@"videos"];
        for (NSDictionary *dic in array) {
            LOLSomeOneProgramListModel *model = [[LOLSomeOneProgramListModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [resultArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            self.result(resultArray);
        });
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
  
    
}


猜你喜欢

转载自blog.csdn.net/liuya000/article/details/48295871