views:

27

answers:

1

Hi,

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]

Thanks in advance....

+2  A: 

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
Georg Fritzsche
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
@Nik: Good additions, but 1. only applies for file scope variables.
Georg Fritzsche
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
@Nik: Nevermind regarding 1., that was one of my C vs. C++ confusions :/
Georg Fritzsche
@Georg: 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