【问题标题】:Objective-C: Passing object to initializerObjective-C:将对象传递给初始化程序
【发布时间】:2015-03-24 12:57:14
【问题描述】:

我有一堂课:
.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: 方法时会出现问题。 那时itemsnil
我做错了什么?

我已经阅读了http://qualitycoding.org/objective-c-init/https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html 和一些 stackoverflow 的答案,但我就是不知道我的问题的根源是什么。

谢谢。

【问题讨论】:

  • 你确定你的初始化器被调用了吗? (设置断点进行检查。)
  • 并且items 被定义为“强”。
  • 是的,我确定。我明确地打电话给init,并在那里设置了断点。它被称为。
  • items 属性很强大——你可以在.h 文件中看到它。

标签: objective-c memory-management


【解决方案1】:

刚刚发现问题:

我一直在创建我的接口实例作为另一种方法中的局部变量。

- (void)viewDidLoad {
    ...

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

它在该方法结束时自动释放。

取出实例属性。现在好了。

抱歉打扰了。

【讨论】:

    猜你喜欢
    • 2021-03-02
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 2011-10-16
    • 2014-10-07
    相关资源
    最近更新 更多