Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy loading in objective C

Tags:

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

like image 746
Rocker Avatar asked Jan 08 '10 07:01

Rocker


People also ask

What is lazy loading in Objective C?

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.

What is lazy loading in IOS?

What is lazy loading: The phrase “lazy loading” is used to describe the act of downloading pictures in layman's terms. As a result, the software does not become unresponsive as images are downloaded.


2 Answers

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.
like image 66
Adrian Kosmaczewski Avatar answered Oct 08 '22 06:10

Adrian Kosmaczewski


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).

like image 20
nevan king Avatar answered Oct 08 '22 06:10

nevan king