-2

My Questing is

-(ABC*)createInstance
{
  Static ABC *obj = [[alloc ABC] init];

  if(obj == nil)
  {
    obj = [[alloc ABC] init];
  }
  return obj
}

can we write in objective c

[[ABC createInstance] release]
royhowie
  • 11,075
  • 14
  • 50
  • 67
Deepak
  • 97
  • 1
  • 5

1 Answers1

2

Yes, users could release your instance if you haven't overridden retain/release. Take a look at common singleton patterns for better approaches.

Notes:

  • It is [ClassName alloc], not [alloc ClassName]
  • If you meant to make createInstance a class method use + (ABC*)createInstance;
  • It is static, not Static
  • You have to initialize obj to nil
  • Use self instead of ABC if subclassing is a concern: [self alloc]
  • The common name for these methods is sharedInstance
Community
  • 1
  • 1
Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
  • I'd add: 1. You **must** initialize the static storage variable with nil (non-primitives do not work). 2. You should use `self` instead of `ABC` for allocation (for subclassing). 3. The accessor should be named `sharedInstance` (common objc style). – Nikolai Ruhe Jul 10 '10 at 09:32
  • @Nik: Good additions, but 1. only applies for file scope variables. – Georg Fritzsche Jul 10 '10 at 09:39
  • 1. Oh, good, I wasn't aware of this difference. 2. It should be `[self alloc]` since it's a class method (of course). – Nikolai Ruhe Jul 10 '10 at 09:45
  • @Nik: Nevermind regarding 1., that was one of my C vs. C++ confusions :/ – Georg Fritzsche Jul 10 '10 at 09:51
  • Yes, after looking into http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1336.pdf (and testing using gcc), I find that static storage duration variables in function local scopes can only be initialized with integral values. – Nikolai Ruhe Jul 10 '10 at 09:59