2012-02-25 9 views
0

В приведенном ниже примере кода, я немного потерял, почему я получаю NZombie на линии:Рекомендации по управлению памятью - как обращаться с зомби?

[Category getInitialDataToDisplay:[self getDBPath]]; 

Я просмотрел С.О. сообщений и другой документации, но я новичок в Objective-C, и я вращая мои колеса на этом.

- (void)applicationDidFinishLaunching:(UIApplication *)application { 

//Copy database to the user's phone if needed. 
[self copyDatabaseIfNeeded]; 

// Init the Array 
activeCategories = [[NSMutableArray alloc] init]; 
activeSubjects = [[NSMutableArray alloc] init]; 
categories = [[NSMutableArray alloc] init]; 
subjects = [[NSMutableArray alloc] init]; 
quotes = [[NSMutableArray alloc] init]; 
quoteMaps = [[NSMutableArray alloc] init]; 

//Initialize the Category array. 
NSMutableArray *tempArray = [[NSMutableArray alloc] init]; 
self.categories = tempArray; 
[tempArray release]; 

//Once the db is copied, get the initial data to display on the screen. 
[Category getInitialDataToDisplay:[self getDBPath]]; 


//populate active subjects and categories: 

activeCategories = [self getActiveCategories]; 
activeSubjects = [self getActiveSubjects]; 

// sort data 

NSSortDescriptor *categorySorter; 
NSSortDescriptor *subjectSorter; 

categorySorter = [[NSSortDescriptor alloc]initWithKey:@"category_title" ascending:YES]; 
subjectSorter = [[NSSortDescriptor alloc]initWithKey:@"title" ascending:YES]; 

NSArray *sortDescriptorsCat = [NSArray arrayWithObject:categorySorter]; 
NSArray *sortDescriptorsSub = [NSArray arrayWithObject:subjectSorter]; 

[self.categories sortUsingDescriptors:sortDescriptorsCat]; 
[self.subjects sortUsingDescriptors:sortDescriptorsSub]; 

[categorySorter release]; 
[subjectSorter release]; 

// Configure and show the window 
[window addSubview:[navigationController view]]; 
[window makeKeyAndVisible]; 
} 

...

- (void)dealloc { 

[activeSubjects release]; 
[activeCategories release]; 

[categories autorelease]; 
[subjects autorelease]; 
[quotes autorelease]; 
[quoteMaps autorelease]; 
[navigationController release]; 
[window release]; 
[super dealloc]; 
} 

Вот getInitialDataToDisplay:

+ (void) getInitialDataToDisplay:(NSString *)dbPath { 

// Use this section to bring in database and populate the array 
FMDatabase *database = [FMDatabase databaseWithPath:dbPath];  
[database open]; 

QuotesAppDelegate *appDelegate = (QuotesAppDelegate *)[[UIApplication sharedApplication] delegate]; 


//appDelegate.categories = [appDelegate.categories sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; 

//POPULATE THE SUBJECT 
FMResultSet *result_subjects = [database executeQuery:@"select * from SUBJECT"]; 

while([result_subjects next]) { 

    NSInteger primaryKey = [result_subjects intForColumn:@"SUBJECT_ID"]; 
    Subject *sub = [[Subject alloc] initWithPrimaryKey:primaryKey]; 

    sub.title = [result_subjects stringForColumn:@"SUBJECT"]; 
    sub.category_title = [result_subjects stringForColumn:@"CATEGORY"]; 
    sub.active = [result_subjects intForColumn:@"ACTIVE"]; 
    sub.isDirty = NO; 

    [appDelegate.subjects addObject:sub]; 
    [sub release]; 

} 

FMResultSet *result_categories = [database executeQuery:@"select distinct category from SUBJECT"]; 

while([result_categories next]) { 

    Category *cat = [[Category alloc] init]; 

    cat.category_title = [result_categories stringForColumn:@"CATEGORY"]; 
    NSLog(@"loading category: %@", cat.category_title); 

    QuotesAppDelegate *appDelegate = (QuotesAppDelegate *)[[UIApplication sharedApplication] delegate]; 

    for (Subject *sb in appDelegate.subjects){ 

     if([cat.category_title isEqualToString:sb.category_title]){ 
      [cat.subjects addObject:sb]; 
      NSLog(@" Adding subject: %@ cat.subjects.count=%i", sb.title, cat.subjects.count); 

     } 

    } 

    [appDelegate.categories addObject:cat]; 
    [cat release]; 

} 

//POPULATE THE QUOTES 
FMResultSet *result_quotes = [database executeQuery:@"select * from QUOTE"]; 

while([result_quotes next]) { 

    Quote *sub = [Quote alloc]; 

    sub.quote_id = [result_quotes stringForColumn:@"QUOTE_ID"]; 
    sub.quote_date = [result_quotes stringForColumn:@"DATE"]; 
    sub.title = [result_quotes stringForColumn:@"DESC1"]; 
    sub.desc2 = [result_quotes stringForColumn:@"DESC2"]; 
    sub.excerpt = [result_quotes stringForColumn:@"EXCERPT"]; 
    sub.note = [result_quotes stringForColumn:@"NOTES"]; 
    sub.isDirty = NO; 

    [appDelegate.quotes addObject:sub]; 
    [sub release]; 

}  


//POPULATE THE QUOTE_MAPS 
FMResultSet *result_quote_map = [database executeQuery:@"select * from QUOTE_MAP"]; 

while([result_quote_map next]) { 

    QuoteMap *sub = [QuoteMap alloc]; 

    sub.quote_id = [result_quote_map stringForColumn:@"QUOTE_ID"]; 
    sub.quote_map_id = [result_quote_map stringForColumn:@"QUOTE_MAP_ID"]; 
    sub.subject_id = [result_quote_map stringForColumn:@"SUBJECT_ID"]; 
    sub.isDirty = NO; 

    [appDelegate.quoteMaps addObject:sub]; 
    [sub release]; 

}  

[database close]; 

NSLog(@"Count of categories: %i", appDelegate.categories.count); 
NSLog(@"Count of subjects: %i", appDelegate.subjects.count); 
NSLog(@"Count of quotes: %i", appDelegate.quotes.count); 
NSLog(@"Count of quoteMaps: %i", appDelegate.quoteMaps.count); 

} 

Вот это getDbPath:

- (NSString *) getDBPath { 

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES); 
NSString *documentsDir = [paths objectAtIndex:0]; 
return [documentsDir stringByAppendingPathComponent:@"reference.db"]; 
} 
+0

Вы используете ARC или нет? Кроме того, возможно, вы можете показать свой метод getInitialDataToDisplay: class. – Jamie

+3

и ваш метод [self getDBPath]. – Jamie

+1

Также вы не должны использовать [object ** autorelease **] в своем dealloc. Используйте [release объекта]. –

ответ

2

Иногда лучшее, что нужно сделать, это Build-> анализировать (CMD сдвиг б). Это укажет на вашу ошибку сразу почти во всех случаях.

удачи!

+0

Спасибо, Нико, мне нравится внешний вид Build + Analyze, но, честно говоря, я не знаю, что делать с данными. Это моя проблема - я пытаюсь узнать, кому лучше управлять объектами лучше и нужно какое-то направление. – jroyce

+0

Он будет генерировать синюю вкладку, если вы нажмете на вкладку, она будет указывать на строки, которые, по ее мнению, вызвали проблему. https://developer.apple.com/library/mac/#documentation/IDEs/Conceptual/Xcode4TransitionGuide/Debugging/Debugging.html – Nico

1
categories = [[NSMutableArray alloc] init]; 
. 
. 
//Initialize the Category array. 
NSMutableArray *tempArray = [[NSMutableArray alloc] init]; 
self.categories = tempArray; 
[tempArray release]; 

u've установочные категории, затем настройте tempArray, заменив его в категориях на него, тем самым сделав утечку, а затем выпустил temp arrayObject, на который теперь указывают категории, поэтому, если "self.categories" является сохраненным свойством, это будет живой мертвец. там, кажется, что-то не так. мне может понадобиться, чтобы увидеть некоторые больше коды (декларации собственности и их синтез, чтобы убедиться.

является зомби призвал «getInitialDataToDisplay» или «getDBPath» попробуйте разделить его на 2 линии, чтобы узнать точку штырьковой более

0

Я думаю, вы не объявляете категорию как сохраненное свойство в файле .h. Если нет, добавьте следующую строку в вашем файл .h

@property (nonatomic, retain) NSArray Category; 

И синтезировать свойства в ом как-

@synthesize Category; 

Я думаю, что это поможет ....