怎么可能这样呢? UITableView数据源计数怪异行为

时间:2014-07-25 22:20:52

标签: ios objective-c uitableview

我不明白这是怎么可能的,或者为什么会这样。谁能给我一个想法?

我添加了更多代码来帮助您解决问题,但是,我不确定额外的代码将如何帮助您。

NSMutableArray *messages = [[NSMutableArray alloc] init];

PFUser *currentUser = [PFUser currentUser];

PFQuery *query = [PFQuery queryWithClassName:@"message"];

[query whereKey:@"receiver" equalTo:currentUser.objectId];

[query orderByDescending:@"createdAt"];

[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

    if (!error && objects !=NULL) {
        NSMutableArray *listOfLastMsgs = [[NSMutableArray alloc] init];
        for (PFObject *object in objects) {
            Boolean *tester = false;
            for(int i = 0;i<listOfLastMsgs.count;i++){


                if([[object objectForKey:@"sender"] isEqualToString:[[listOfLastMsgs objectAtIndex:i] objectForKey:@"sender"]]){
                    tester = true;
                }
            }
            if(!tester){
                [listOfLastMsgs addObject:object];
            }
        }

        for(int i = 0;i<listOfLastMsgs.count;i++){
            NSString *s = [[listOfLastMsgs objectAtIndex:i] objectForKey:@"message"];

            if(s.length > 80){
                s = [s substringToIndex:80];
            }
            [messages addObject:s];

        }

        NSLog(@"in did load %lu", (unsigned long)messages.count);
        [self.tableView reloadData];
    } else {
        // Log details of the failure
        NSLog(@"Error: %@ %@", error, [error userInfo]);
    }
}];


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.

NSLog(@"in number of rows %lu", (unsigned long)messages.count);
return messages.count;
}

这是我的输出日志

2014-07-25 18:15:32.980 myapp[5696:60b] in number of rows 0
2014-07-25 18:15:35.990 myapp[5696:60b] in did load 2
2014-07-25 18:15:35.991 myapp[5696:60b] in number of rows 0

1 个答案:

答案 0 :(得分:2)

假设您viewDidLoad中存在大量代码,问题很简单 - 您在messages设置了一个本地viewDidLoad变量,而您的numberOfRowsInSection正在引用未初始化的messages实例变量。

假设您确实在messages中有一个名为viewDidLoad的ivar,请更改:

NSMutableArray *messages = [[NSMutableArray alloc] init];

为:

messages = [[NSMutableArray alloc] init];