IconoclastLabs/rubymotion_cookbook

Immutable - ch_13 / 03 _ creatingsaving

Closed this issue · 4 comments

Hi,

I'm trying to see how I can save info twice - which brings up the "Can't modify an immutable model"

This is what happens when the perform_save is run twice. Is there any way to go about it?

Thanks!

def viewDidLoad
view.backgroundColor = UIColor.lightGrayColor

self.title = "Core Data"

@label = UILabel.new
@label.text = 'No Errors'
@label.frame = [[0,50],[UIScreen.mainScreen.bounds.size.width,50]]
view.addSubview(@label)

perform_save
perform_save

end

Hey Wadner,

I believe the issue here is that perform_save was truly constructed in a procedural mind set (basically a flat derivation from the book). The app can be run twice, which causes two saves, but to save twice inside one run, we're going to need to pull out some of the redundancy, or continue with a procedural paradigm.

Easiest way, is duplicate lines 35 to 54, where we insert a person into the model. Doing so will create 2 people in one run.

If you want to do it cleaner, we can take the initialize portion (above line 35) and put that in it's own method that gets called once (like the object's initialization), and then what's left will be the aforementioned lines; able to be called twice.

Why the model is being changed:
The model and context are kept in memory by the @ symbol, so when the method runs a second time it's trying to modify the existing model (even if it is just setting it to the same values), which it is not allowed to do.

I hope this helps you save info twice. If you're still confused, let me know and I can probably modify this chapter so perform_save can be run twice right out the box. A lot of these lessons could be a lot cleaner once in ruby, but we don't want to re-factor them so much they don't reflect the iOS examples we're working with.

Hi GantMan,

Thank you for your reply. I've tried a few times and am just stumped. Delete and Create is fine, but with update - the model just keeps becoming frozen (even when .dup and .clone is used).

Will definitely take up on your offer of seeing a method for updating/saving a particular record twice (or more).

Hey Wadner,

Pushed a double save example on 13.03, I hope this helps!

Thank you GantMan! It works. Awesome.

Time for me to port it over to test then.

Have a great weekend!