我有一节课:
.H
@interface NoticesDataSource : NSObject <UITableViewDataSource>
@property (nonatomic,strong) NSMutableArray *items;
@end
的.m
@implementation NoticesDataSource
...
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[self items] count];
// return [_items count];
}
- (instancetype)initWithItems:(NSMutableArray *)items {
self = [super init];
[self setItems:items];
// _items = items;
return self;
}
- (instancetype)init {
self = [super init];
[self setItems:[self prepareItems]];
// _items = [self prepareItems];
return self;
}
- (NSMutableArray *)prepareItems {
NSMutableArray *items = [[NSMutableArray alloc] init];
...
[items addObject:item];
...
[items addObject:item];
return items;
}
...
@end
调用方法tableView:numberOfRowsInSection:
时出现问题。
那时items
是nil
我做错了什么?
我已经阅读了http://qualitycoding.org/objective-c-init/,https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html和一些stackoverflow答案,但我无法弄清楚问题的根源是什么。
感谢。
答案 0 :(得分:0)
刚发现问题:
我一直在另一个方法中创建一个接口实例作为局部变量。
- (void)viewDidLoad {
...
NoticesDataSource *noticesDataSource = [[NoticesDataSource alloc] init];
self.noticesTableView.dataSource = noticesDataSource;
}
在该方法的最后,它被自动释放。
将其移到实例属性中。现在没关系。
很抱歉打扰。