I have a problem with one property in one class. I am coding with iOS 6.1 if it makes any difference.
The class is UIViewController
and the property is the declared in the header file like so:
// Keeps track of time in seconds
@property (nonatomic, strong) NSNumber *timeInSeconds;
In my implementation file I use the property during 3 occasions:
one is to add time with the method
- (void)addTime
one is to subtract time with the method
- (void)subtractTime
Those two methods use the property like so:
- (void)addTime
{
CGFloat timeFloat = [self.timeInSeconds floatValue];
// Here I set the value of the property timeInSeconds, but I can't access that value later on in the code!
self.timeInSeconds = [NSNumber numberWithFloat:timeFloat +5];
NSLog(@"Total Time:%@", self.timeInSeconds);
}
The two methods addTime
and subtractTime
do what they are supposed to do, and they keep a good track of the property timeInSeconds
value as I add then subtract then add...
The problem is when I call in the same implementation file the third method which is:
- (void)updateLabelTime
{
self.label.attributedText = [[NSAttributedString alloc]initWithString:[self.timeInSeconds stringValue]];
[self.label setNeedsDisplay];
[NSTimer scheduledTimerWithTimeInterval:0.8 target:self selector:@selector(updateLabelTime) userInfo:nil repeats:YES];
}
I also tried to create a the NSAttributedString
with stringWithFormat
instead of initWithString
but the problem persists which is that instead of returning the value of the property timeInSeconds
which i previously set using addTime
and subtractTime
, it calls the getter which creates a new instance of timeInSeconds
since in my getter I have lazy instantiation.
I tried to not write the getter/setter for the property (since I am using iOS 6.1) but it makes no difference.
If I just set the label to some random string, it would work. The problem is that if I know the value of timeInSeconds
is 55, it would still create a new _timeInSeconds
.
I tried my best with my English since I am French, please don't answer if the question was already asked by a beginner iOS developer and just redirect me. I couldn't find an answer though, thanks!
EDIT: Here is the custom getter
- (float)timeInSeconds
{
if (!_timeInSeconds) {
_timeInSeconds = 0;
}
return _timeInSeconds;
}
SECOND EDIT:
The stupid beginner mistake that I made was that addTime and subtractTime are actually implementing a protocol and they set the property which "lives" in another class which is why I could not access it! That other class that needs the protocol was creating a new instance of the class where addTime and subtractTime is written.
What needs to be done is to set the controller as the delegate for the protocol. I did this in the viewDidLoad method with something like:
self.view.delegate = self;
Thanks for all the help.