【发布时间】:2011-01-31 22:22:17
【问题描述】:
NSArray 有一个奇怪的问题,我的数组中的一些对象成员超出了范围,但其他成员没有:
我有一个名为 Section 的简单对象。 它有3个成员。
@interface Section : NSObject {
NSNumber *section_Id;
NSNumber *routeId;
NSString *startLocationName;
}
@property(nonatomic,retain) NSNumber *section_Id;
@property(nonatomic,retain) NSNumber *routeId;
@property(nonatomic,retain) NSString *startLocationName;
@end
@implementation Section
@synthesize section_Id;
@synthesize routeId;
@synthesize startLocationName;
//Some static finder methods to get list of Sections from the db
+ (NSMutableArray *) findAllSections:{
- (void)dealloc {
[section_Id release];
[routeId release];
[startLocationName release];
[super dealloc];
}
@end
我从数据库中用一个名为findAllSection的方法填充它
self.sections = [Section findAllSections];
在查找所有部分中,我创建了一些局部变量,用 db 中的数据填充它们。
NSNumber *secId = [NSNumber numberWithInt:id_section];
NSNumber *rteId = [NSNumber numberWithInt:id_route];
NSString *startName = @"";
然后新建一个Section,并将这些局部变量的数据存储在Section中
Section *section = [[Section alloc] init];
section.section_Id = secId;
section.routeId = rteId;
section.startLocationName = startName;
然后我将部分添加到数组中
[sectionsArray addObject:section];
然后我清理,释放局部变量和我添加到数组中的部分 [secId 发布]; [rteId 发布]; [开始名称发布]; [locEnd_name 释放];
[section release];
在所有部分的循环中重复(释放局部变量,部分在每个循环中完成)
方法返回,我检查了数组,所有的部分都在那里。我似乎无法进一步挖掘以查看数组中 Section 对象的值(这可能吗)
稍后我尝试检索其中一个部分
我从数组中得到它
Section * section = [self.sections objectAtIndex:row];
然后检查值
NSLog(@" SECTION SELECTED:%@",section.section_Id);
但是对section.section_Id 的调用由于section.section_Id 超出范围而崩溃。
我检查了这个 Section 对象的其他成员,他们都没事。 经过一些试验和错误,我发现通过注释掉成员变量的释放对象就可以了。
//[secId release];
[rteId release];
[startName release];
[locEnd_name release];
[section release];
我的问题是:
我打扫得好吗?
我应该释放添加到数组中的对象和函数中的局部变量吗?
我的 dealloc 在 Section 中可以吗?
这段代码看起来没问题,我应该在别处寻找问题吗?
我没有做任何复杂的事情,只是从数据库中填充数组,在表格单元中使用它。
我可以注释掉这个版本,但更想知道为什么它会起作用,以及我是否不应该这样做。唯一释放secId 的地方是dealloc。
【问题讨论】:
标签: objective-c memory-management nsarray