3

I want to use iOS charts for my objective-c project. Since the UI is written in code completely, I don't want to create a nib file for the chart view specifically. However, a simple init or initWithFrame to create the LineChartView is giving me 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];

Here, self.chartView is nil after calling above code.

jerry
  • 274
  • 2
  • 19
  • 1
    make the property as strong instead of weak. Also where do you init the property, post the complete code. – Teja Nandamuri Sep 06 '17 at 20:53
  • That worked !! Can you explain a little as to why it didn't work with the weak property ? IBOutlets are usually marked as weak. – jerry Sep 07 '17 at 01:06
  • 1
    `weak` will release it immediately once its created, since there's no other strong object retain it – Tj3n Sep 07 '17 at 05:38

1 Answers1

1

As per my exprience you need to remove Weak property only nonatomic will work while you are assigning object with Init method.

@property (nonatomic, weak) LineChartView *lineChart;

This one should replaced with

@property (nonatomic) LineChartView *lineChart;

as if you create weak property it will release after its assignment.

also while you make this type of mistake XCode throws warning like below :

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.

So in-sort never use weak while you are assigning any retain object in it.

Hope this will help!

CodeChanger
  • 7,953
  • 5
  • 49
  • 80