iOS - 内存分析

来源:互联网 发布:mac版steam怎么汉化 编辑:程序博客网 时间:2024/05/16 04:46

Demo1:

先贴上DemoSource代码:

#import <Foundation/Foundation.h>#import <UIKit/UIKit.h>@interface DemoSource : NSObject <UITableViewDataSource>- (id)initWithItems:(NSArray *)items;@property (nonatomic, strong) NSArray *items;@end

#import "DemoSource.h"@implementation DemoSource- (id)initWithItems:(NSArray *)items{    self = [super init];    if (self) {        _items = items;    }    return self;}#pragma mark UITableViewDataSource- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    return self.items.count;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    static NSString *identifier = @"cell";    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];    if (!cell) {        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];    }    cell.textLabel.text = [NSString stringWithFormat:@"%@",self.items[indexPath.row]];    return cell;}@end
开始我们的主视图DemoTableViewController : UITableViewController,运行效果如图:


从上图看出程序crash,一般来说,出现EXC_BAD_ACCESS错误的原因都是悬挂指针导致的。但具体是哪个指针是悬挂指针还不确定,因为控制台并没有给出具体crash信息。这里需要启动NSZombieEnabled以便得到更多的crash信息。步骤如图:


这时候再次运行效果如图:


然后点击上图红色框内按钮,效果如图:


看上图标注的两个红色框,它们两个地址是一样,而且DemoSource前面有个_NSZombie_修饰符,说明dataSource对象被释放了但仍然在使用。这时回过头来看dataSource声明属性的修饰符是assign(assign属性的作用是:简单赋值,不更改索引计数),所以这里只需改成retain(retain属性的作用是:release旧的对象,将旧对象的值赋予输入对象,再提高输入对象的索引计数为1或者strong(ARC下的strong和MRC下的retain一样)修饰即可运行通过。

0 0