Question

I have a "always keep a static reference on the last created object" pattern for one of my classes. When I create a new instance of it, the static pointer should been set to this new instance. Solved the way below:

static AViewController *actualSelf = nil;

+ (AViewController *) getActualSelf {
    return actualSelf;
}

- (AViewController *) init {
    self = [super init];
    self.title = @"Title";

    actualSelf = nil; // Why do I need this line the second time init gets called?

    actualSelf = self; // this is the only line which sets actualSelf

    return self;
}

- (void)dealloc {
    actualSelf = nil;
}

…SOME IMPORTANT MUST BE MISSING, BUT I DON'T KNOW WHAT
  • create AViewController a > Init gets called > Static pointer is set to a
  • create AViewController b > Init gets called > Static pointer should be set to b. But the static pointer is not set to b! It's sets itself from a to nil!

Object a is most of the time deallocated before b gets created.

Do I always need to reset the static variables to nil when deallocating them? NO, see my own answer below.

Without the line "actualSelf = nil;", through ARC object a gets deallocated in the moment actualSelf is set to object b.

Was it helpful?

Solution 2

  • create AViewController a > Init gets called > Static pointer is set to a
  • create AViewController b > Init gets called > Static pointer should be set to b. But the static pointer is not set to b! It's sets itself from a to nil!

Probably nothing other than actualSelf has ownership of a. Therefore, actualSelf = self; during the initialization of b causes a to be fully released and thus deallocated. During the -dealloc of a, it sets actualSelf to nil. Apparently, this is coming after the assignment of actualSelf to the new self (object b). (The precise order of operations of the ARC-supplied -release call vis-a-vis the assignment of actualSelf is unpredictable.)

The very fact that you are assigning actualSelf to nil in the -dealloc method smells bad. It suggests that actualSelf should be __weak because if it's holding a strong reference to an object, then that object can't be deallocated.

At the very least, -dealloc should test if actualSelf equals self before resetting it. But that will never be true so long as actualSelf is a strong reference, since a strongly referenced object can't be deallocated.

This whole approach is deeply problematic. What are you really trying to accomplish?

OTHER TIPS

actualSelf = nil; // WHY DO I NEED THIS LINE?

You don't need the line, it accomplishes nothing and will probably be eliminated by the compiler optimizer in a release build.

The class is not a singleton.

The rest of the answer has been deleted because the question has been modified.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top