Leaky Custom Object用于存储plist中的数据

时间:2012-03-05 21:34:44

标签: iphone objective-c ios

我制作了一个非常简单的自定义对象pictureData

这是.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];
    }

一切都很糟糕。我有一个表视图加载正确的图片图像和信息,没有问题。在运行Instruments for leaks时,我看到我的pictureData对象在每次分配时都会泄漏。

我认为通过自动释放我的对象,我不必担心手动分配和解除分配它们。

也许我的问题是我使用autorelease,autoReleasePool保留+1的保留计数,然后当我向我的数组添加pictureData对象时,它还保留了它?谢谢大家的时间!

编辑:别忘了给超级打电话!谢谢山姆!

2 个答案:

答案 0 :(得分:1)

将dealloc更改为:

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

(致电[super dealloc]

答案 1 :(得分:-1)

在您的函数中,更改返回值以包含自动释放,例如

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

将pictureData对象添加到dataSource时,会增加保留计数,因此您应该在返回时自动释放它。

希望它有所帮助。