无法使用模型在cellForRowAtIndexPath中获取数据

时间:2018-06-05 13:58:50

标签: ios objective-c json model-view-controller

我有一个json API文件,我想在我的tableview单元格中填充。 但是,如果你们都能弄清楚我的错误在哪里,我就无法得到数据并感激不尽。谢谢!

ViewController.m 在cellForRowAtIndexPath中,值将变为null。如何将我的json数据传递给AddressItem模型和

@property (strong , nonatomic)NSMutableArray<AddressItem *> *aryAddressData;
@property (nonatomic, strong) AFHTTPSessionManager *manager;
@property (nonatomic,strong) NSMutableArray *aryAddressList;

- (void)setUpAdrressData
{

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    ...
    manager.requestSerializer = serializer;


    NSDictionary *params = @{@"user_id": @(1)};

    [manager POST:@"http://.net/api/member_address" parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {

        _aryAddressList = responseObject;
        self.aryAddressData=[NSMutableArray array];
        for (NSDictionary *subDic in _aryAddressList) {

            AddressItem *model=[[AddressItem alloc]initWithDic:subDic];
            [self.aryAddressData addObject:model];
            NSLog(@"110 %@",model.address_1);
            NSLog(@"110 %@",model.address_2);
           //I CAN GET VALUE HERE
        }

    } failure:^(NSURLSessionTask *operation, NSError *error) {
        NSLog(@"IF ERROR");
    }];

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddressCell *cell = [tableView dequeueReusableCellWithIdentifier:AddressCellID forIndexPath:indexPath];
    cell.addressItem = _aryAddressData[indexPath.row];
    return cell;
}

MODEL.h

#import "JSONModel.h"
#import <Foundation/Foundation.h>

@interface AddressItem : JSONModel

@property (nonatomic, copy) NSString *address_1;
@property (nonatomic, copy) NSString *address_2;

- (instancetype)initWithDic:(NSDictionary *)dic;

@end

MODEL.m

#import "AddressItem.h"
#import "NSString+Utils.h"

@implementation AddressItem

- (instancetype)initWithDic:(NSDictionary *)dic{
    NSError *error = nil;
    self =  [self initWithDictionary:dic error:&error];
    return self;
}

VIEWCELL.h

#import <UIKit/UIKit.h>
@class AddressItem;
@interface AddressCell : UITableViewCell
@property (strong , nonatomic)AddressItem *addressItem;
@end

VIEWCELL.m

- (void)setAddressItem:(AddressItem *)addressItem
{
    _addressItem = addressItem;
    NSLog(@"202 - %@", addressItem.address_1);
    NSLog(@"202 - %@", addressItem.address_2);
    //NO VALUE HERE AS WELL

}

1 个答案:

答案 0 :(得分:2)

对Api的调用是异步的,您需要在填充数组后重新加载表

for (NSDictionary *subDic in _aryAddressList) {

    AddressItem *model=[[AddressItem alloc]initWithDic:subDic];
    [self.aryAddressData addObject:model];
    NSLog(@"110 %@",model.address_1);
    NSLog(@"110 %@",model.address_2);

}
dispatch_async(dispatch_get_main_queue(), ^{
  [self.tableView reloadData];
});