Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Static class in Objective C"

I need to know how I can make static method and static property like static method in java...

Thanks

Maxime

like image 533
Maxime Avatar asked Apr 29 '11 19:04

Maxime


People also ask

What is static in Objective-C?

"In both C and Objective-C, a static variable is a variable that is allocated for the entire lifetime of a program.


1 Answers

As others have pointed out, static class methods are prefixed with a plus (+) in declaration, like this:

@interface MyClass : NSObject
   + (void)myClassMethod;
@end

Objective-C does not make static properties quite as simple, and you need to jump through the following hoops:

  1. declare a static variable
  2. set up getter and setter methods for access to it
  3. retain it's value

Complete example:

static NSString* _foo = nil;

@interface MyClass : NSObject
   + (NSString *)getFoo;
   + (void)setFoo;
@end

// implementation of getter and setter
+ (NSString *) getFoo {
  return _foo;
}

+ (void) setFoo:(NSString*) value {
  if(_foo != value) {
    [_foo release];
    _foo = [value retain];
  }
}

// optionally, you can set the default value in the initialize method
+ (void) initialize {
  if(!_foo) {
     _foo = @"Default Foo";
  }
}

I am not an Obj-C expert, but this seems to work well in my code. Correct me if anything here is off.

like image 177
Michael Teper Avatar answered Nov 15 '22 21:11

Michael Teper