[英]Objective-C leak problem
根據儀器,我在下面的代碼中有泄漏。 有誰能給我一些建議和解釋,為什么我會在這些方面得到適應症?
以下幾行被標記為泄漏:
NSMutableArray *read_Question = [[NSMutableArray alloc] initWithCapacity: 0];
NSArray *fetchedObjects = [qContext executeFetchRequest:fetchRequest error:&error];
if ([[info valueForKey:@"idQ"] intValue] == questionNr) {
[read_Question addObject:[info valueForKey:@"question"]];
所以這是完整的代碼:
- (NSMutableArray *)readQuestion: (int)questionNr {
NSMutableArray *read_Question = [[NSMutableArray alloc] initWithCapacity: 0];
NSError *error;
//=========PREPARE CORE DATA DB===========//
if (managedObjectContext == nil) { managedObjectContext = [(FamQuiz_R0_1AppDelegate *)
[[UIApplication sharedApplication] delegate] managedObjectContext]; }
// Define qContext
NSManagedObjectContext *qContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"questions" inManagedObjectContext:qContext];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [qContext executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
if ([[info valueForKey:@"idQ"] intValue] == questionNr) {
[read_Question addObject:[info valueForKey:@"question"]];
[read_Question addObject:[info valueForKey:@"qRightAnswer"]];
[read_Question addObject:[info valueForKey:@"qWrongAnswer1"]];
[read_Question addObject:[info valueForKey:@"qWrongAnswer2"]];
}
}
[fetchRequest release];
[read_Question autorelease];
return read_Question;
}
那是分配對象的地方,但不是泄漏對象的地方。 儀器可以告訴對象何時分配以及在何處保留和釋放對象,但是不知道哪個釋放對應於哪個保留,因此它將泄漏歸因於初始分配。
查找這些對象的使用位置。 Instruments中有一個視圖可以顯示塊的歷史記錄,但是最好還是仔細考慮一下。 哪些代碼保留了這些對象? 您能證明在所有情況下都可以釋放相同的代碼嗎?
您是否在自動釋放池中自動釋放? 即您是否在調用-read_Question
的線程中創建了NSAutoreleasePool
的實例? 我假設這在主線程中被調用,並且您的main.m
文件默認情況下將如下所示:
int main(int argc, char* argv[]) {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool drain];
return retVal;
}
我不認為這是您的問題,但是如果沒有全部詳細信息,我還是會這樣說-如果在另一個線程中調用-read_Question
則需要類似的內容:
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
.
.
.
[self read_Question];
.
.
.
[pool drain];
否則,請參閱@Steven的建議!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.