内存泄漏,重新分配NSArray属性

时间:2012-03-07 10:53:03

标签: iphone objective-c memory-management memory-leaks

我有一个由UITableView属性支持的NSArray。 Array被声明为属性:

@property (nonatomic, retain) NSArray *events;

@synthesize events;

并用于以下方法。仪器不断告诉我populateEvents导致泄漏。我已尝试过此代码的多种变体,但最终会出现更多泄漏或EXC_BAD_ACCESS

- (void)viewDidLoad
    {
        self.events = [self populateEvents];
    }

    - (void)updateData
    {   
        events = nil;
        self.events = [self populateEvents];

        [self.tableView reloadData];
    }

    - (NSArray*)populateEvents
    {
        NSMutableArray *response = [[NSMutableArray alloc] init];

        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM Event"];
        sqlite3_stmt *statement = [database prepare:sql];

        if(statement != nil)
        {
            // Loop through the results and add them to the response
            while(sqlite3_step(statement) == SQLITE_ROW)
            {
                Event *event = [[Event alloc] init];
                event.subject = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
                e

                [response addObject:event];
                [event release];
            }
            sqlite3_finalize(statement);
        }
        return [response autorelease];
    }

更新 很多人都在询问活动类别:

@interface Event : NSObject

@property (nonatomic) NSInteger Id;
@property (nonatomic, retain) NSString *subject;
@property (nonatomic, retain) NSString *details;
@property (nonatomic, retain) NSString *startTime;
@property (nonatomic, retain) NSString *endTime;
@property (nonatomic, retain) NSString *eventType;
@property (nonatomic, retain) NSString *employee;

@end

- (void)dealloc
{
    [super dealloc];

    [subject release];
    [details release];
    [startTime release];
    [endTime release];
    [eventType release];
    [employee release];
}



- (NSString*)startTime
{
    return [self humanReadableDate:startTime];
}



- (NSString*)endTime
{
    return [self humanReadableDate:endTime];
}



- (NSString*)humanReadableDate:(NSString*)isoDate
{
    NSDateFormatter* formatter = [[[NSDateFormatter alloc]init]autorelease];
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];

    NSDate* date = [formatter dateFromString:isoDate];

    [formatter setDateFormat:@"MMM dd yyyy HH:mm"];
    NSString* humanrReadable = [formatter stringFromDate:date];

    return humanrReadable;
}
@end

4 个答案:

答案 0 :(得分:4)

这是一个泄漏,因为您将NSArray(事件)的指针更改为nil而不释放前一个对象。你丢失了指向前一个数组的指针,因此泄漏了。

改变你的

events = nil;

self.events = nil;

答案 1 :(得分:1)

问题在于

event = nil;

由于您的属性设置为retain,因此事件指向nil而不释放先前的内存。

你可以致电self.events = [self populateEvents]; 在分配并保留obj之前,它将首先释放先前的obj。

答案 2 :(得分:1)

您应该在Events之前发布内部对象调用[super dealloc]

并在updateData方法中删除events = nil;。它是不必要的,即使您修复了Events类,也会导致问题。

答案 3 :(得分:1)

只需在XCode项目组和文件窗格中设置此环境变量, 你会发现可执行文件 - >您的申请 - >右键单击 - >获取信息 - >参数选项卡 - >环境变量

名称:NSZombieEnabled
价值:是

这将帮助您找到对象的僵尸对象,如果有任何对象在释放该值时不止一次发布。

最好的运气!