views:

113

answers:

2

Quick question, my data model is a singleton object and it contains a list of names that I want to archive. My idea is to make the model responsible for loading and saving it's own data. The model's load method will be called by the ViewController's viewDidLoad method and save by the ViewController's applicationWillTerminate. I could do the load/save directly within the ViewController, but this would be messy as the list of names are an instance variable of the model.

gary

+2  A: 

You could just load and save in the init and dealloc methods (although it's common to call a save method explicitly). It's a good idea to encapsulate it within the model class. If you're loading from the network you might want to have a separate loadData method or something, rather than doing it from init.

Felixyz
init might be a good idea, I had not considered that. It also makes sense as now I am allocating some of the instance variables there. When I implement to load (via archiving/NSCoding) I will need to load if a save file is found or alloc if not, so having both together will be helpful.
fuzzygoat
+1  A: 

Apple recommends using lazy initialization wherever possible, so I think you're heading down the right path, though you might want to consider making the method name something that looks like a property accessor, e.g. -names rather than -load (especially since there's a class method named +load that means something quite different).

jlehr
There are plenty of UIKit instance methods that start with "load", so I don't agree on that point. Since this is a singleton that is (one suspects) used widely in the app, I think it makes sense to load the data immediately, but I agree that in general it's good not to initialize fields until necessary. Whether it makes sense to do loading for each property separately in the accessors depends on the context I think. Sometimes it might be better to load and init all at once, especially if you load an object's content from the network. But other times this might be inefficient of course.
Felixyz
I don't think I suggested that there's any particular downside to using 'load' as a prefix in a longer method name. However, since `+load` is declared in NSObject, and is therefore inherited by all of its descendants (pretty much everything), I'd shy away from naming an instance method just plain old `-load`, but that's just me.
jlehr
I probably should have been clear, I was using "load" and "save" simply to refer to the actions concerned and not to imply that I would be using them as method names. Given what I am doing they will probably end up being "loadCore" or "loadReactor".
fuzzygoat
@jlehr: I read carelessly and I agree that -load on its own isn't a good idea.
Felixyz