sxross / MotionModel

Simple Model and Validation Mixins for RubyMotion
MIT License
192 stars 67 forks source link

Data not being persisted #116

Closed andersennl closed 9 years ago

andersennl commented 9 years ago

I've just tried out the gem and for me it doesn't seem to permanently save the data. When I do:

Car.create(doors: 4)

It's only persisted as long as I don't restart the simulator. When I do, Car.all returns 0 again. Am I missing something here? Apart from this, this gem looks really promising! Thanks!

sxross commented 9 years ago

Please look over the section in the README on persistence. You can persist as often or as seldom as you choose. For example, one of my apps listens for all MotionModel changes and calls the persistence methods. A different app only persists when the app enters background because the primary data source is cloud based and MotionModel's copy is only for offline situations.

Let me know if this clarifies things.

andersennl commented 9 years ago

I hope that I've found the correct solution in the readme. If I want to persist after every save, is it correct to call Car.serialize_to_file(file_name = 'Car') right after the creation of the new object and Car.deserialize_from_file(file_name = 'Car') after the app launches (inside the AppDelegate)?

sxross commented 9 years ago

That's a good way to conceptualize it. Loading at startup is important. When you persist is different. If you call the serialize* method on the main thread, you block the UI. I set up an observer when I start my app that listens for MM changes. See the notifications section of the README. In the code executed on the data change, I can persist without blocking.

Make sense?

andersennl commented 9 years ago

Thanks, I think I understand what you mean, but why doesn't it block the UI when doing it this way? Does the dataDidChange method run on a background thread (because of the NSNotificationCenter)?

sxross commented 9 years ago

It's asynchronous because it's running on a notification, and those just don't happen when the UI is active. If you want to go a step further, look at this post of mine. Near the bottom, I discuss actually spinning the persist off into a different thread.

http://sxross-blog.herokuapp.com/2013/02/05/more-about-lifecycle-and-some-async-stuff-tossed-in/

andersennl commented 9 years ago

Ok I understand, thank you very much for the explanation and the link.