iMinichrispy
iMinichrispy

Reputation: 144

Adding a New Time to a Total Time

What I am trying to do is add up the total time a player has stayed alive in a game. So, each time the game starts, I start a timer, and when the player dies, I terminate the timer. Every time this happens, I want this new time to be added up into a total time spent alive. This is my code:

int newTime = [newTimeLabel.text intValue];
int totalTime = [totalTimeLabel.text intValue];
int newTotalTime = newTime + totalTime;
totalTimeLabel.text = [NSString stringWithFormat:@"Total Time: %d",newTotalTime];

However, this the totalTimeLabel.text keeps displaying only the new time, not the newTime added to the previous total time. I'm not sure what I am doing wrong.

An example of what I am trying to achieve:

Trial 1:
newTime = 5
totalTime = 0
newTotalTime = 5 + 0 = 5

Trial 2:
newTime = 7
totalTime = 5
newTotalTime = 7 + 5 = 12

Trial 3:
newTime = 3
totalTime = 12
newTotalTime = 3 + 12 = 15

And so on...

Upvotes: 0

Views: 69

Answers (1)

jhabbott
jhabbott

Reputation: 19281

The problem is that you are trying to use UI elements (the View in Model-View-Controller) to store your application state/data (The Model in Model-View-Controller).

You should use some data variables of appropriate types to store your total accumulated time and your new time, and you should add these together and keep track of them completely independently of the UI (View).

If these values are transient (i.e. only need to be maintained for the life of the Controller) then it's ok (from a practical point of view, not a pure MVC one) to skip the whole Model part and just have the two variables in your Controller. Then whenever you update them you should also update the View by setting the labels. I recommend this approach for now.

However, if the user closes the app and comes back later, wouldn't it be nice if those values persisted? In which case, you should implement a persistent data-Model, and those values would be stored there so that you can retrieve them even after an app shutdown.

Search for information on the MVC design pattern, you'll find it really helpful in designing and implementing apps. It will help you avoid silly mistakes that will come back to bite you later on :)

Upvotes: 1

Related Questions