iOS 图表 - 如何以编程方式初始化 LineChartView

iOS Charts - How to initialize LineChartView programmatically

我想为我的 objective-c 项目使用 iOS 图表。由于 UI 完全用代码编写,我不想专门为图表视图创建一个 nib 文件。然而,一个简单的 initinitWithFrame 来创建 LineChartView 给了我 nil

//Declare chartView property in header
@property (nonatomic, weak) LineChartView* chartView;

//Call to init chart     
CGRect frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 
CGRectGetHeight(self.view.bounds));
self.chartView = [[LineChartView alloc] initWithFrame: frame];

这里调用上面代码后self.chartView为nil

根据我的经验,您需要删除 Weak 属性 只有 nonatomic 在您使用 Init 方法分配对象时有效。

@property (nonatomic, weak) LineChartView *lineChart;

这个应该替换为

@property (nonatomic) LineChartView *lineChart;

就好像你创建了 weak 属性 它会在分配后释放。

当您犯此类错误时,XCode 也会发出如下警告:

warning: assigning retained object to weak property; object will be released after assignment [-Warc-unsafe-retained-assign] self.lineChart = [[LineChartView alloc] initWithFrame:CGRectMake(0, 0, 320, 320)]; ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1 warning generated.

因此,当您在其中分配任何 retain 对象时,请不要使用 weak

希望这会有所帮助!