iphone - CoreData内存管理问题

标签 iphone cocoa xcode core-data

我正在使用 Coredata 并拥有一个具有以下 toMany 关系的数据模型:

Rooms.isUsedBy -> Class many classes use a Room
Class.hasStudents -> Students many Students are in a Class

鉴于房间,我希望获得所有使用该房间的学生。 这是简化的代码:

-(void) studentsinRoom:(Room*)aRoom {
    NSSet* roomStudents = [[NSSet alloc]init];
    for (SchoolClass* aClass in aRoom.isUsedBy) {
        roomStudents = [roomStudents setByAddingObjectsFromSet:aClass.hasStudents];
    }
    [roomStudents release];
}

roomStudents 计算正确。
但是,当退出该方法时,我收到“EXC_BAD_ACCESS”错误。

我正在 iPhone 模拟器中对此进行调试。

我很确定我在内存管理方面做了/没有做正确的事情。 我确实在“malloc_error_break”上设置了中断,但它没有被击中。

最佳答案

将其更改为:

- (void) studentsinRoom:(Room*)aRoom
{
    NSSet* roomStudents = nil;
    for (SchoolClass* aClass in aRoom.isUsedBy)
    {
        roomStudents = [roomStudents setByAddingObjectsFromSet:aClass.hasStudents];
    } 
}

setByAddingObjectsFromSet:方法返回一个自动释放的NSSet对象,所以你不想自己释放它。当自动释放池耗尽并且已释放的对象再次释放时,您将获得 EXC_BAD_ACCESS

顺便说一句,名称 hasStudents 似乎令人困惑,听起来像是一个 bool 值 - 我认为只有 students 会让代码更容易阅读这种一对多关系。

关于iphone - CoreData内存管理问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1191338/

相关文章:

iphone - 清除 MKMapView 的图 block 缓存吗?

iphone - 为什么我无法将文件写入应用程序的文档目录?

ios - 将 CUSTOM 元数据保存在从 iOS 中的 AVFoundation 获取的图像中

objective-c - 找不到 Cocoa/Cocoa.h(错误)

objective-c - 如何在选择 NSOutlineView 的行时设置背景颜色

ios - 根据环境变量调整 Xcode Build 设置值

objective-c - 应用程序提交 iOS 的 Bundle ID

ios - 关于 UITabBarController,有没有办法在选择新选项卡时强制完全释放 View

objective-c - 如何分析一段代码在 Objective-C/Cocoa 中执行所需的时间以进行优化

ios - 如何创建 View 以添加到 View Controller ?