LoginSignup
0
0

More than 5 years have passed since last update.

Objective-C 中的 Class Variable

Last updated at Posted at 2015-10-02

Objective-C 中其實沒有 class variable 這種東西,不過可以透過存取 C 的 static variable 來達成這個目的。

運用的背景

當在寫一個 service object/class 或是 manager 的時候,並不是都需要初始化一個 singleton (單例)的 sharedManager 之類的擺在那邊。

像是寫公司服務內部的 API service 的時候,需要存 API key 或 application name 等等,我並不想要在初始化一個 NSObject 之類的物件,只是拿來存這些字串。我只是想保留這些資訊、接著透過幾個 class methods 來存取就好。

實作

這邊會示範如何建立一個這種機制。

建立一個殼

首先可以先建立一個繼承自 NSObject 的物件,然後寫一組可以存取的 method :

MyManager.h
#import <Foundation/Foundation.h>

@interface MyManager : NSObject

+ (void)setAPIKey:(NSString *)APIKey;
+ (NSString *)APIKey;

@end

接著先加入 class method 的殼

MyManager.m

#import "MyManager.h"

@implementation MyManager

+ (void)setAPIKey:(NSString *)APIKey {
}

+ (NSString *)APIKey {
  return nil; 
}

@end

加入 methods 的實作

這時候,只要在實作檔裡面加入一個 static variable 即可,變數可隨意命名。

我在這裡會習慣把 private 的變數命名成容易辨別的名稱,前面再加底線方便辨識。

MyManager.m

#import "MyManager.h"

static NSString *_APIKey;

@implementation MyManager

+ (void)setAPIKey:(NSString *)APIKey {
  _APIKey = APIKey
}

+ (NSString *)APIKey {
  return _APIKey; 
}

@end

成果

這樣,在引入 MyManager.h 之後,就可以不用透過初始化 MyManager 的情形下,直接存取 APIKey 了。

SomeClass.m

#import "MyManager.h"

@implementation SomeClass

- (void)someMethod {
  [MyManager setAPIKey:@"abc123"];
  NSLog(@"APIKey: %@", [MyManager APIKey]);
}

@end

試試看吧~!

如果有內容上的錯誤或是疑問,歡迎在下面留言討論 :smile:

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0