ninja_iOS
ninja_iOS

Reputation: 1223

object creation in block

Im trying to create view controller in my block call and when its returning from block my object becomes nil. How to fix it?

my block declaration:

typedef void (^GetViewController)(UIViewController *viewController, int index);

calling block when VC is needed (viewController is nil now)

self.getViewController(viewController, index);

setting VC in another class

self.myController.getViewController = ^(UIViewController *viewController, int index)
{
    switch (index) {
        case Option1:
            viewController = [[Option1VC alloc] init];
            break;
        case Option2:
            viewController = [[Option1VC alloc] init];
            break;
        default:
            break;
    }
//at this point VC is created
};

Upvotes: 0

Views: 75

Answers (3)

Khanh Nguyen
Khanh Nguyen

Reputation: 11132

Pointer to pointer is an option, ie

typedef void (^GetViewController)(UIViewController** viewController, int index);

...

self.myController.getViewController = ^(UIViewController** viewController, int index)
{
    *viewController = nil; // Avoid random value

    switch (index) {
        case Option1:
            *viewController = [[Option1VC alloc] init];
            break;
        case Option2:
            *viewController = [[Option1VC alloc] init];
            break;
        default:
            break;
    }
//at this point VC is created
};

Upvotes: 1

timgcarlson
timgcarlson

Reputation: 3146

You can use the __block storage type modifier on variables to modify them in a block. Without this modifier, variables are read-only in the scope of the block. This should get you around passing the parameter by value.

Apple's __block variables documentation

Upvotes: 0

Duncan C
Duncan C

Reputation: 131436

Your block is modifying a parameter that is passed to it. Parameters are passed by value, so the changed value is discarded.

Why not make the block return a view controller as the block result? That way the compiler should generate code so that it stays alive until the caller has a chance to assign the result to a strong variable.

Upvotes: 4

Related Questions