【发布时间】:2014-11-12 18:25:07
【问题描述】:
我在将数据从 NSMutableArray 填充到 UITableView 时遇到问题。在ViewDidLoad 中,我进行了一个网络调用,它从 Parse 获取数据并返回一个名为“journalEntries”的NSMutableArray,然后我将此数组中的数据复制到名为“allEntries”的NSMutableArray 变量中。我在这里设置了一个断点并验证了_allEntries 有4 个对象(不是nil)。但是,当涉及到numberOfRowsInSection 方法时,_allEntries.count 返回 4 但我在这里设置了一个断点,_allEntries 中的所有对象都变为nil。
- (void)viewDidLoad {
[super viewDidLoad];
_allEntries = [[NSMutableArray alloc] init];
[MMDatabaseHelper getAllJournalEntries:^(NSMutableArray *journalEntries) {
for (MMJournalEntry *entry in journalEntries)
[_allEntries addObject:entry];
// I set a breakpoint here and verified that _allEntries has 4 objects
[self.tableView reloadData];
}];
下面这个方法返回 4 但 allEntries 数组中的所有对象都是 nil。在 viewDidLoad 中它们不是 nil。
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return _allEntries.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
MMJournalEntry *currentEntry = _allEntries[indexPath.row];
return cell;
}
编辑1:第一张截图是网络调用完成时。第二个是numberOfRowsInSection方法
编辑 2:这是getAllJournalEntries 方法
+(void) getAllJournalEntries:(void(^)(NSMutableArray *journalEntries))callback {
PFQuery *query = [PFQuery queryWithClassName:JournalTable];
[query findObjectsInBackgroundWithBlock:^(NSArray *entries, NSError *error) {
if(entries != nil && entries.count > 0) {
NSMutableArray *mainEntries = [[NSMutableArray alloc] init];
for (PFObject *entry in entries) {
//convert to journal entry...
MMJournalEntry *je = [[MMJournalEntry alloc] init];
je.objId = entry.objectId;
je.textContent = entry[@"textContent"];
je.createdByUserId = entry[@"createdByUserId"];
je.cityStateName = entry[@"cityStateName"];
je.lattitude = entry[@"lattitude"];
je.longitude = entry[@"longitude"];
je.lattitude = entry[@"lattitude"];
je.tags = [NSMutableArray arrayWithArray:[entry[@"tags"] componentsSeparatedByString:@","]];
je.numberOfHearts = entry[@"numberOfHearts"];
[mainEntries addObject:je];
}
callback(mainEntries);
}
else
callback(nil);
}];
}
【问题讨论】:
-
NSArray(或NSMutableArray)的元素不能是nil。如果您将_allEntries中的“对象”视为nil,则说明您的调试器或您对其输出的解释有问题。 -
_allEntries的声明在哪里?如果它是 viewController 的 @property,也许可以尝试self.allEntries代替?无论如何都不应该直接访问支持的 ivar。此外,例如,如果您尝试访问第 10 行的条目,但只有 5 个条目,则该数组索引没有任何值。确认该条目仍然存在是个好主意。 -
在 cellForRow... NSLog 你的 _allEntries 对象。它可能为零(将记录为
(null))。 NSArray 中有 nil 条目是非法的。 -
getAllJournalEntries:在哪个队列上调用其完成处理程序?很容易想象reloadData在后台队列中不起作用。在这种情况下,您对-tableView:numberOfRowsInSection:被称为-viewDidLoad的假设不一定成立。 -
您能否显示您的
MMJournalEntry对象的定义 - 特别是它的属性声明 - 看起来它们正在被释放
标签: ios uitableview nsmutablearray