简体   繁体   中英

“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

In Objective-C those are called class methods, and they are prefaced with a plus sign (+)

@interface MyClass : NSObject

+ (void)myClassMethod;
- (void)myInstanceMethod;

@end

Static methods in Objective C are known as class methods and start with a '+' sign, eg:

+ (void)aStaticMethod 
{
    // implementation here
}

Static variables are declared using the static keyword.

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.

You cannot have static properties generated automatically but you can create a getter and a setter static methods manually.

+ (NSObject *) myStaticValue;
+ (void)setMyStaticValue:(NSObject *)value;

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

you can declare it in the implementation file of your class. It should comes before the @implementation compiler directive. But that static variable can use only within its class. you can use it via your own getter-setter methods not by property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM