首页 > 解决方案 > TableViewController 不显示表信息

问题描述

嗨,当我执行 for 循环以从集合中获取所有文档时。我将汽车对象添加到 NSMutablearray 中,当我调试时,我可以看到对象被添加到数组中,但是当我希望它显示在表中并获取数组的计数时,我调用 [self.mycars 计数]得到计数,但计数为零,我无法从 cell.textLabel.text = vehicle.name 获取信息;所以我做错了什么。

#import "TableViewController.h"
#import "Car.h"
#import "Vehicle.h"

@interface TableViewController ()

@end

@implementation TableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;

    self.db = [FIRFirestore firestore];
    self.myCars = [[NSMutableArray alloc] init];


    [[[[self.db collectionWithPath:@"users"] documentWithPath:[FIRAuth auth].currentUser.uid]
      collectionWithPath:@"cars"] getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *error) {
        if (error != nil) {
            NSLog(@"Error getting documents: %@", error);
        } else {
            for (FIRDocumentSnapshot *document in snapshot.documents) {
                NSLog(@"%@ => %@", document.documentID, document.data);
                Car *car = [[Car alloc] initWithCarName:[document valueForField:@"carname"] andCarStyle:[document valueForField:@"carstyle"]
                                           andCarColour:[document valueForField:@"colour"] andCarYear:[document valueForField:@"caryear"]
                                            andCarDoors:[document valueForField:@"doors"] andCarSeat:[document valueForField:@"seat"] andCarWheels:[document valueForField:@"wheels"]
                                     andCarTankCapacity:[document valueForField:@"tankcapacity"] andCarHorsePower:[document valueForField:@"horsepower"] andCarModelName:[document valueForField:@"modelname"]];

                NSLog(@"Car name:%@", car.name);

                [self.myCars addObject:car];

            }
        }
    }];

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.myCars count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellidentifier" forIndexPath:indexPath];

    // Configure the cell...'
    Vehicle *vehicle = [self.myCars objectAtIndex:indexPath.row];
    cell.textLabel.text = vehicle.name;

    return cell;
}



@end

标签: iosobjective-cfirebasegoogle-cloud-firestore

解决方案


您需要在更改/更新数据源(self.myCars在这种情况下)后手动重新加载数据,这意味着您需要[self.tableView reloadData];在 for 循环之后添加。如果它仍然无法正常工作,您可能需要检查是否self.myCars已初始化。


推荐阅读