views:

172

answers:

4

Hi everyone. I heard lazy loading technique quite helpful to increase the performance of the programme. I am developing games for iPhone. I am not sure how is the way to apply lazy loading in objective C. Could anyone show me the example please?

Thanks in advance

+1  A: 

Don't load anything until you have to load something. Then, when you have to load it, load it.

anthony
+2  A: 

Here's an example of lazy loading from the Core Data template:

- (NSManagedObjectModel *)managedObjectModel
{
    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];
    return managedObjectModel;
}

The first time the managedObjectModel is asked for, it is created by the code. Any time after that, it already exists (!= nil) and is just returned. That's one example of lazy loading. There are other kinds, such as lazy loading of NIB files (loading them into memory only when they're needed).

nevan
+4  A: 

The general pattern for lazy loading is always more or less the same:

- (Whatever *)instance
{
    if (_ivar == nil)
    {
        _ivar = [[Whatever alloc] init];
    }
    return _ivar;
}
  1. In your class, add an ivar of the type you need, and initialize that to nil in the constructor;
  2. Create a getter method for that ivar;
  3. In the getter, test for nil. If so, create the object. Otherwise, just return the reference to it.
Adrian Kosmaczewski
A: 

Thanks a lot these help me much

Rocker
Then you should mark an answer as solution. That's just polite and nice to those who've taken the time to answer your question. It gives you reputation, too.
MrMage
Ah I din't know this...people been telling me about reputation but I don't know how to gain it. Thanks for helping mate
Rocker
I can just mark one question as an answer? what about there are few good answers to that question too?
Rocker