0
votes

I have a class:
.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

The problem occures when method tableView:numberOfRowsInSection: is called. At that point items is nil.
What am I doing wrong?

I've already read http://qualitycoding.org/objective-c-init/, https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html and some stackoverflow answers, but I just can't figure out what is the root of my problem.

Thanks.

1
Are you sure your initializer is called? (Set a breakpoint to check.) - Drux
And is items defined to be "strong". - Hot Licks
Yes, I'm sure. I'm calling init explicitly, and have set breakpoint there. It is called. - Ilia Liachin
items property is strong — you can see it in .h file. - Ilia Liachin

1 Answers

0
votes

Just found the problem:

I've been creating an instance of my interface as a local variable in another method.

- (void)viewDidLoad {
    ...

    NoticesDataSource *noticesDataSource = [[NoticesDataSource alloc] init];
    self.noticesTableView.dataSource = noticesDataSource;
}

It was autoreleased in the end of that method.

Took it out to the instance property. Now it's ok.

Sorry for bothering.