2

I am cleaning up my code in a phonebook iPhone application and the Leaks tool in Instruments is reporting that I am leaking NSCFString objects. Here is the pattern that I am following:

I have a Person class in my application that has nothing more than local NSString members and associated properties for first name, last name, etc.

My view controller has an NSMutableArray property that is populated from a SQLite database in the searchBarSearchButtonClicked event. This NSMutableArray is populated with Person object(s) that will be used to populate my tableview control. Also, if the user clicks on a person in the view, their Person object will be passed to the Detail view for viewing additional information than just the name.

When I perform my first look up and display the results there are no memory leaks.

Now, when I perform my second look up I would ideally like to clear out the NSMutableArray and reload it with the new result set without leaking memory. So, to do this, I call removeAllObjects on my personList property and then call the database to repopulate the personList NSMutableArray as shown below:

[self.personList removeAllObjects];
self.personList = [SearchService GetPersonList:searchText];
[list reloadData];

By calling removeAllObject I've gotten rid of the leaks that I used to have that were associated with the Person objects. However, it appears that I am now leaking the NSString objects left over from the properties of the individual Person objects.

Is this possible?

I am new to the Instruments tool but from what I can tell from the Extended Detail when I drill into one of the NCSFString leaks is that last line of code in the stack is often pointing to the @synthesize line of code for the property, such as:

@synthesize firstName;

So, that is why I think those NSStrings are not getting cleaned up. Is there a better way to do this that doesn't produce memory leaks?

4

1 回答 1

3

您是否在Person 类的方法中释放NSStrings ?dealloc

假设您这样设置您的财产:

@property (retain) NSString *firstName;

当您firstName使用 setter 进行设置时,它将被保留。如果Person实例随后被释放并解除分配,但firstName尚未释放,它将泄漏。

把它放在deallocPerson班级的方法中:

- (void)dealloc
{
    [firstName release];
    [super dealloc];
}

(假设用于您的firstName属性的相应 ivar 被调用firstName)。

于 2009-08-26T15:27:25.537 回答