空数组的索引 0 超出范围 parse.com

index 0 beyond bounds for empty array parse.com

我正在尝试将当前用户创建的对象列表解析为来自 Parse.com 的自定义 table 视图。我在 运行 时收到此错误:

[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array

这是我的做法:

@interface ProfileViewController ()

@property (nonatomic, retain) PFQuery *query;

@end

@implementation DailyProfileViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self refresh];

    self.tableView.delegate = self;
    _projects = [[NSMutableArray alloc] initWithCapacity:100];
}

- (void)refresh {

    PFQuery *query = [PFQuery queryWithClassName:@"Projects"];
    [query includeKey:@"user"];
    [query whereKey:@"user" equalTo:[PFUser currentUser]];
    [query orderByDescending:@"createdAt"];

    [query findObjectsInBackgroundWithBlock:^(NSArray *posts, NSError *error) {
        if (!error) {

            [_projects setArray:posts];
            [self.tableView reloadData];
            NSLog(@"%@", posts);
            return;
        }
        NSLog(@"Fetch posts error: %@", error.localizedDescription);
        return;

    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _projects.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 65;
}

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

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    _project = [_projects objectAtIndex:indexPath.row];

    ProfileProjectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ProfileProjectTableViewCell"];

        if (!_user) _user = [PFUser currentUser];

        cell.item = _project;

        [(PFFile*)_project[@"profilePic"] getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
            cell.profilePic.image = [UIImage imageWithData:data];
        }];

        [(PFFile*)_project[@"bgImage"] getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
            cell.bgView.image = [UIImage imageWithData:data];
        }];

        cell.projectName.text = _project[@"name"];

        return cell;
}

@end

为什么在初始化数组之前调用 - refresh?将您的 -viewDidLoad 更改为:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.delegate = self;
    _projects = [[NSMutableArray alloc] init];
    [self refresh];
}

请像这样更改您的 viewDidLoad..

self.tableView.delegate = self;
_projects = [[NSMutableArray alloc]init];
    [self refresh];

你应该在初始化数组后调用刷新方法,并确保你添加的数据不能为空