iPhone - Memory leaks in NSSortDescriptor
I am receiving memory leaks using the following code:
Interface:
@property (nonatomic, retain) NSArray *sortedItems;
Implementation:
NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"ScannedDate" ascending:NO] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [self.items sortedArrayUsingDescriptors:sortDescriptors];
self.sortedItems = [NSArray arrayWithArray:sortedArray]; // memory leak 100% here
- (void)viewDidUnload {
开发者_StackOverflow中文版self.sortedItems = nil;
[super viewDidUnload];
}
- (void)dealloc {
[sortedItems release];
[super dealloc];
}
Well, you are creating two unnecessary arrays.
Replace this:
NSArray *sortedArray = [self.items sortedArrayUsingDescriptors:sortDescriptors];
self.sortedItems = [NSArray arrayWithArray:sortedArray]; // memory leak 100% here
... with this:
self.sortedItems = [self.items sortedArrayUsingDescriptors:sortDescriptors];
Every time you create an array, you send a retain
to the objects held by the array. If the array is autoreleased (which the convenience methods above do create) then the point at which their release
messages is sent is uncontrolled by the programmer. This can produce apparent leaks depending on circumstances at runtime.
精彩评论