i am testing UITableView : (under ARC) code as below,
- (void)viewDidLoad
{
[super viewDidLoad];
UnitTest *unitTest = [[UnitTest alloc] init];
UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
tableView.delegate = unitTest;
tableView.dataSource = unitTest;
[self.view addSubview:tableView];
}
i have implement tableView delegate in Object UnitTest. when i run my project, it fetch a error:
libobjc.A.dylib`objc_msgSend:
0x30f13f68: teq.w r0, #0
0x30f13f6c: beq 0x30f13faa ; objc_msgSend + 66
0x30f13f6e: push.w {r3, r4}
0x30f13f72: ldr r4, [r0] // Thread 1: BAD_EXE_ACCESS ....
0x30f13f74: lsr.w r9, r1, #2
0x30f13f78: ldr r3, [r4, #8]
0x30f13f7a: add.w r3, r3, #8
0x30f13f7e: ldr r12, [r3, #-8]
and there is nothing in console.
when i change the line
UnitTest *unitTest = [[UnitTest alloc] init];
to
UnitTest *unitTest = [UnitTest sharedUnitTest]; // i have implement this singleton
Everything works OK!! why
You're in ARC, and it means something here. Basically, your unitTest
will get deallocated sooner or later as you don't keep any reference to it. But still, it's both the delegate and dataSource of the tableView. Thus, after some time (to simplify), the tableView will try to call its delegate, but the unitTest
will have been deallocated.
Thus, the simplest solution here, is to create a property for the unitTest
: @property (nonatomic, strong) UnitTest *unitTest;
in your header, synthesize it in your .m
Then, just use:
self.unitTest = [[UnitTest alloc] init];
It should fix it all. You probably don't need a singleton for this.
PS: the reason why the singleton fixes this issue is that the singleton will "live forever" (as long as the app is launched). As it never gets deallocated, no issue when the table view tries to call its delegate/dataSource.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.