嗨,当我执行for循环以从集合中获取所有文档时。我将汽车对象添加到NSMutablearray中,当我调试时,我可以看到对象正在添加到数组中,但是当我希望它在表中显示并获取数组的计数时,我将其称为[self.mycars count]获取计数,但计数为零,我无法从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
答案 0 :(得分:2)
在更改/更新数据源(在这种情况下为self.myCars
之后,您需要手动重新加载数据,这意味着您需要在for循环之后添加[self.tableView reloadData];
。如果仍然无法正常工作,则可能要检查self.myCars
是否已初始化。