[英]Memory leak with UITableView and NSFetchedResultsController
[英]Simple UITableView memory leak
我在一個簡單的應用程序中出現內存泄漏問題。 該代碼摘自《 iPhone iOS Development Essentials》一書。 代碼如下:
h文件
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
<UITableViewDelegate, UITableViewDataSource>
@property (strong, nonatomic) NSArray *colorNames;
@end
和m文件
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize colorNames;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.colorNames = [[NSArray alloc] initWithObjects:@"blue", @"red",@"green",@"yellow", nil];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
self.colorNames = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.colorNames count];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil)
{
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [self.colorNames objectAtIndex:[indexPath row]];
return cell;
}
@end
每當我嘗試使用iPhone模擬器滾動表格時,都會發生48k的內存泄漏。 你知道泄漏在哪里嗎?
假設您不使用ARC
例如,僅當 @property
colorNames
是保留名稱時,
NSArray* cArray = [[NSArray alloc] initWithObjects:@"blue", @"red",@"green",@"yellow", nil];
self.colorNames = cArray;
[cArray release];
另外,一旦創建單元,就會autorelease
單元。
if(cell==nil)
{
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
編輯如果單擊該內存泄漏,儀器可以將您帶到造成泄漏的特定代碼行。
希望能幫助到你。
我有同樣的問題,已經發布了一個錯誤報告。 支持人員回答我,他們知道問題所在,該Bug仍處於打開狀態,並且ID為#10703036。
即使在4.3.2更新Xcode之后仍在等待...
您應該使用@synthesize
colorNames
代替:
@synthesize colorNames = _colorNames;
這將創建一個ivar名稱_colorNames
。
現在使用:
_colorNames = [[NSArray alloc] initWithObjects:@"blue", @"red",@"green",@"yellow", nil];
使用self.colorNames = [[NSArray ...
是您的屬性colorNames
被保留了兩次。 一次通過您屬性的屬性(強),一次通過調用“ alloc”。
在viewDidUnload
您應該使用:
[_colorNames release];
_colorNames = nil;
瀏覽不同的論壇,我找到了答案(我希望)。 由於泄漏來自lib system_c.dlib和負責的strdup框架,因此人們聲稱這是Apple庫中的一個包。 使用UIPickerView,UIDatePicker和UIScrollView控制器發現了相同的問題。 相同的大小(48字節),相同的庫和相同的幀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.