0

I want to keep one single object in application, and do not release.

@implementation MyClass

    static MyClass *sharedInstance = nil;
    + (MyClass *)sharedInstance {
        if (!sharedInstance) {
            sharedInstance = [[super alloc] init];
        }
        return sharedInstance;
    }
@end

I can get single object by [MyClass sharedInstance], it works well in Non-ARC mode.

But the object will release when change to ARC mode.

Cœur
  • 34,719
  • 24
  • 185
  • 251
why
  • 22,477
  • 27
  • 94
  • 137
  • 2
    The code you have written here is correct, if not threadsafe. If the object is getting deallocated, the problem is elsewhere. – Chuck Mar 07 '13 at 07:20
  • Make a Object of MyClass in AppDelegate. – Gopesh Gupta Mar 07 '13 at 07:21
  • 1
    Why are you calling `[super alloc]`? It should be `[self alloc]` or `[MyClass alloc]`. Also, why is `sharedInstance` static variable of type `MyClass` and the return type of the `sharedInstance` class method `Ap`? They need to be the same. – rmaddy Mar 07 '13 at 07:34
  • Sorry , I have solved it myself! – why Mar 07 '13 at 07:36
  • 1
    See http://stackoverflow.com/questions/5720029/create-singleton-using-gcds-dispatch-once-in-objective-c for a better way to create a singleton. – rmaddy Mar 07 '13 at 07:37

1 Answers1

3

Why do you think it would release? You've assigned it to a static variable tracked by ARC.

nneonneo
  • 162,933
  • 34
  • 285
  • 360
  • The reason is not that the variable is declared `static`, but that its storage duration is static, same as all file scope variables. In this context `static` only means internal linkage. – Nikolai Ruhe Mar 07 '13 at 07:45