【发布时间】:2012-01-18 06:21:36
【问题描述】:
在我的应用程序中,我有一个到 sqlite3 数据库的连接。我做了一个包装类,在这个包装类中我有一个 NSMutableDictionary 和 NSMutableArray。
每次运行查询时,我都会从字典和说唱歌手类中的数组中removeAllObjects(我不释放它)。然后我将查询的结果添加到数组和字典中。该词典包含另一个子词典。
我有一个 tableViewController,在这个类中,我使用我的 rapper 类从数据库中获取数据并将其复制到我的 tableviewcontroller 变量中:
.h
@interface BrandViewController : UIViewController
<UITableViewDataSource , UITableViewDelegate>
{
FairPriceDatabaseView *FairPriceDB;
NSArray *brandsIDs;
NSMutableDictionary *brandsRecords;
UITableView *tableView;
}
.m
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self loadBrandsIDs];
[tableView reloadData];
}
- (void)dealloc {[brandsRecords release];
[brandsIDs release];
[super dealloc];
}
-(NSArray *) loadBrandsIDs
{
[self loadBrandsDB];
[brandsIDs release];
brandsIDs = [[FairPriceDB getBrandIDs]copy];
[brandsRecords release];
**brandsRecords = [[FairPriceDB getBrandIDs_NSDictionary]copy];**
[FairPriceDB release];
FairPriceDB = nil;
return brandsIDs;
}
- (FairPriceDatabaseView *) loadBrandsDB {
if (!FairPriceDB)
FairPriceDB = [[FairPriceDatabaseView alloc] initWithFairPriceDatabaseViewFilename:@"b.db"];
return FairPriceDB;
}
在测试时,我在星号行出现内存泄漏 (brandsRecords = [[FairPriceDB getBrandIDs_NSDictionary]copy];)
当我更改 tableviewcontroller 并回到这些 tableviewcontrollers 时发生内存泄漏....
我想知道,我这样做是否正确?为什么会漏水?
另外,我每次发布NSMutableDictionary时,是否还需要发布其中包含的子词典?
FairPriceDataBaseViewController.h(包装类)
@interface FairPriceDatabaseView {
NSMutableArray * idList;
NSMutableDictionary * recordList;
}
FairPriceDataBaseViewController.m(包装类)
- (NSArray *) getBrandIDs {
NSDictionary * row;
[idList removeAllObjects]; // reset the array
for (row in [self getQuery:@"SELECT productID,brandName FROM product GROUP BY brandName;"])
[idList addObject:[row objectForKey:@"productID"]];
return idList;
}
-(NSDictionary *) getBrandIDs_NSDictionary{
[recordList removeAllObjects];
[idList removeAllObjects];
[self getBrandIDs];
NSNumber * rowid;
for(rowid in [self idList])
[recordList setObject:[self getProductRow:rowid] forKey:rowid];
return recordList;
}
- (NSDictionary *) getProductRow: (NSNumber *) rowid {
self.tableName = @"select * from product where productID = ?";
return [self getRow:rowid];
}
-(FairPriceDatabaseView *) initWithFairPriceDatabaseViewFilename: (NSString *) fn
{
if((self = (FairPriceDatabaseView *) [Super initWithDBFilename:fn]))
{
idList = [[NSMutableArray alloc] init];
recordList = [[NSMutableDictionary alloc]init];
}
[self setDefaults];
return self;
}
【问题讨论】:
-
你能把getAllrecordByRecords的代码贴出来吗?
-
这就是您的真实代码,还是您记忆中的代码?顺便说一句,调用您的实例变量
NSArray...不是一个好习惯。变量名应该以小写字母开头,当然不应该与框架类的命名空间冲突。 -
很抱歉,因为这是我第一次在表单上发布问题,现在我添加了所有真实的代码,还有一个说唱歌手类...
标签: iphone objective-c memory-management memory-leaks nsdictionary