"Static class in Objective-C"

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

thanks

Maksim

+8
objective-c iphone
source share
5 answers

In Objective-C, they are called class methods, and they are preceded by a plus sign (+)

@interface MyClass : NSObject + (void)myClassMethod; - (void)myInstanceMethod; @end 
+12
source share

Static methods in Objective-C are known as class methods and begin with a + sign, for example:

 + (void)aStaticMethod { // implementation here } 

Static variables are declared using the static .

+11
source share

You cannot create static properties automatically, but you can create static getter and setter methods manually.

 + (NSObject *) myStaticValue; + (void)setMyStaticValue:(NSObject *)value; 
+2
source share

As others have pointed out, static class methods have a prefix with a plus (+) declaration, for example:

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

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

  • declare a static variable
  • configure getter and setter methods to access it
  • save value

Full 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'm not an Obj-C expert, but it seems to work well in my code. Correct me if something is disabled here.

+2
source share

if you want to create a static property, you create a class variable. Properties are used only for instance variable. If you create static, all objects have the same variable; Because it is a class variable.

you can declare it in the implementation file of your class. It should appear before the @implementation compiler directive. But this static variable can only be used inside its class. you can use it with your own getter-setter methods, and not by property.

0
source share

All Articles