2012-03-05 80 views
0

我製作了一個非常簡單的自定義對象pictureData用於存儲plist數據的泄漏自定義對象

這裏是.h文件

#import <Foundation/Foundation.h> 

@interface pictureData : NSObject { 
    NSString *fileName; 
    NSString *photographer; 
    NSString *title; 
    NSString *license; 
} 

@property (nonatomic, retain) NSString  *fileName; 
@property (nonatomic, retain) NSString  *photographer; 
@property (nonatomic, retain) NSString  *title; 
@property (nonatomic, retain) NSString  *license; 

+(pictureData*)picDataWith:(NSDictionary*)dictionary; 

@end 

.m文件

#import "pictureData.h" 

@implementation pictureData 

@synthesize fileName; 
@synthesize photographer; 
@synthesize title; 
@synthesize license; 

+ (pictureData*)picDataWith:(NSDictionary *)dictionary { 

    pictureData *tmp = [[[pictureData alloc] init] autorelease]; 

    tmp.fileName = [dictionary objectForKey:@"fileName"]; 
    tmp.photographer = [dictionary objectForKey:@"photographer"]; 
    tmp.title = [dictionary objectForKey:@"title"]; 
    tmp.license = [dictionary objectForKey:@"license"]; 

    return tmp; 
} 

-(void)dealloc { 
    [fileName release]; 
    [photographer release]; 
    [title release]; 
    [license release]; 
} 

@end 

我然後設置這些對象的數組,像這樣:

NSString *path = [[NSBundle mainBundle] pathForResource:@"pictureLicenses" ofType:@"plist"]; 

    NSArray *tmpDataSource = [NSArray arrayWithContentsOfFile:path]; 
    NSMutableArray *tmp = [[NSMutableArray alloc] init]; 
    self.dataSource = tmp; 
    [tmp release]; 

    for (NSDictionary *dict in tmpDataSource) { 
     pictureData *pic = [pictureData picDataWith:dict]; 
     NSLog(@"%@", pic.title); 
     [self.dataSource addObject:pic]; 
    } 

一切正常smashingly。我有一個表格視圖加載正確的圖片圖像和信息,沒有問題。運行儀器進行泄漏時,我發現我的pictureData對象在每次分配時都會泄漏。

我會假設與我的對象autoreleased我不會擔心手動分配和釋放他們。

也許是我的問題,我使用autorelease,其中autoReleasePool保留+1計數,然後當我添加一個pictureData對象到我的數組,這也保留了它?謝謝大家的時間!

編輯:別忘了叫超級!謝謝你,山姆!

+0

從你的代碼中,除了你在'dealloc'方法中缺少對'[super dealloc]'的調用外,一切看起來都很好。請注意,這應該是'dealloc'方法的最後一行。另外,'self.dataSource'增加了'pictureData'對象的retainCount。我假設你從這個集合中刪除實例。 – Sam 2012-03-05 21:41:04

回答

1

變化的dealloc到:

-(void)dealloc { 
    [fileName release]; 
    [photographer release]; 
    [title release]; 
    [license release]; 
    [super dealloc]; 
} 

(調用[super dealloc]

+0

謝謝你,Sam,沒有泄漏,一切都好! – Max 2012-03-05 21:50:11

-1

在你的函數,改變返回值,包括自動釋放,像

+ (pictureData*)picDataWith:(NSDictionary *)dictionary 
{ 
    ... 
    ... 
    return [tmp autorelease]; 
} 

當您添加pictureData對象dataSource,你增加了保留計數,所以你應該在返回時自動釋放它。

希望它有幫助。

+0

他已經有autorelease在那裏。如果你添加另一個應用程序可能會崩潰。 – jsd 2012-03-05 22:42:02

+0

哎呀......忽略了那個:-) – vipinagg 2012-03-05 23:30:06