Removing Object With Timer
I have two NSMutableArrays, collectables and collectableViews.
My app consists of a character moving around and gathering collectables (coins, apples, bananas, etc) for points...
I would like the collectables to disappear after a certain amount of time.. however, I am confused as to where to put an NSTimer to not disrupt Model/View/Controller design.
For example, If I put an individual timer in each model, the model doesn't know of the view and cannot remove the view..
If I put the NSTimer in the controller, I would need to make another array consisting of all the collectables on the screen, in order of which one expires first. The timer's method would fire every second and remove each collectable when they are du开发者_运维百科e.
Is there an easier, better way to do this?
Most games model this kind of 'state-monitoring' using one or more game clocks. You can do something like this:
- Create a data structure containing a duration time, function pointer, and array of object variables. For this example let's call it DecayEvent.
- Create a static, mutable array of DecayEvent's in your front (main) controller, with some nice accessor methods
- Choose an appropriate event processing interval. It needs to be large enough to process what you think the maximum number of events will be, but small enough not to retard user experience.
- Create a method on your front controller that will process through the array of decay events. Every time the method is called it will iterate the array and decrement the event's duration time by the event processing interval. If the decay events duration falls below zero then 'fire the event' (basically, trigger its callback function in another thread, with the callback arguments).
- Create an NSTimer in your main thread. Set it to call your processing method at every event processing interval.
You will have to tweak quite a bit to get everything working the way you want, but the steps above will generally work.
Good luck!
Your current situation tends that you should keep timer in your controller because controller has access to each data modal and views you can access arrays too. also another approach is to use NSNotificationCenter. First try and if that doesn't work then let us know.
精彩评论