【问题标题】:iphone: Core Data: NSManagedObjects and UITableView crashiphone:核心数据:NSManagedObjects 和 UITableView 崩溃
【发布时间】:2011-10-09 10:56:56
【问题描述】:

这个 fetch 方法完美运行,NSLog 打印出数据库的内容...(在 NSArray 中获取对象):

NSError *error2;
fetchedObjects = [moc executeFetchRequest:fetchRequest error:&error2];

if (!fetchedObjects) {
    NSLog(@"Error %@",[error2 localizedDescription]);
}

for (NSManagedObject *info in fetchedObjects) {

    NSLog(@"Name: %@", [info valueForKey:@"Name"]);
    NSLog(@"Description: %@", [info valueForKey:@"Description"]);
    NSLog(@"Ingredients: %@", [info valueForKey:@"Ingredients"]);

.. 但是当我尝试填充 tableView 时(我已经构建了许多表,并且觉得我对它们的工作方式有很好的理解),程序在 int retVal = UIApplicationMain(argc, argv, nil 时出现“EXE_BAD_ACCESS”崩溃,无);。”就是这样,没有其他错误信息。

为了尝试调试,我将这个简单的 NSLog 放在“cellForRowAtIndexPath”方法中,但它在 NSLog(@"fetchedObjects count in tableview %i",[fetchedObjects count]) 处崩溃。

据我所知,我还没有发布数组。

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.
    NSLog(@"fetchedObjects count in tableview %i",[fetchedObjects count]);
    NSManagedObject *info3 = [fetchedObjects objectAtIndex:indexPath.row];
    NSLog(@"Name: %@", [info3 valueForKey:@"Name"]);
    cell.textLabel.text = [info3 valueForKey:@"Name"];

【问题讨论】:

  • numberOfRowsInSection 中的行数是多少?您在哪种方法中初始化 fetchedObjects?
  • 嗨普拉文。我使用return [ArrayNameHere count]; 目前是27。这意味着数组在那里......!?!

标签: iphone uitableview core-data nsmanagedobject


【解决方案1】:

看起来您的 fetchedObjects 实例变量由于自动释放池刷新而被释放。

NSManagedObjectContext-executeFetchRequest:error: 方法返回一个 autoreleased NSArray 实例,您没有获得该实例的所有权,因此当执行到达-tableView:cellForRowAtIndexPath: 方法,自动释放池已被刷新,该对象已被释放,您现在有一个悬空指针。啊,经典。

当然,解决方案是将-retain消息发送到返回的NSArray,从发送-executeFetchRequest:error:到你的NSManagedObjectContext

不要忘记在您的 -dealloc 方法中向其发送 -release 消息。

【讨论】:

  • 谢谢雅各布。我将 fetchObjects 复制到另一个数组中:displayArray = [NSArray arrayWithArray:fetchedObjects]; 并打印出内容(一切正常)。我在调用表 reloaddata [displayArray count] 之前检查了数组,这也很好用。将 tableView 更改为指向这个新数组,它仍然在 NSLog 上崩溃 `NSLog(@"displayArray count in tableview %i",[displayArray count]);` 我什至手动创建了另一个数组并将 tableView 指向该表正在工作(确实如此)。为了以防万一,我还清理了几次项目。
  • 终于搞定了。我应该将fetchedObjects 复制到一个新数组中,所以:displayArray = [fetchedObjects mutableCopy]; 使用[NSArray arrayWithArray:fetchedObjects] 复制数组似乎不正确。感谢您的帮助。
  • @Jeremy 创建副本比简单地调用-retain 更昂贵。你真的应该按照我告诉你的去做,而不是复制。这是不必要的开销。
【解决方案2】:

问题似乎出在这一行

NSManagedObject *info3 = [fetchedObjects objectAtIndex:indexPath.row];

尝试使用

NSManagedObject *info3 = [fetchedObjects objectAtIndex:0];

因为您的 UiTableViewCell 计数和 fetchedObjects 计数在整个过程中应该相等。

如果不匹配,则会出现索引错误。

【讨论】:

    猜你喜欢
    • 2011-01-28
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    相关资源
    最近更新 更多