0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

クラス変数の作り方

Posted at

インスタンスを作らないで、その変数にアクセスしたい

要はクラス変数ってこと

Hoge.h

// interfaceの中にかく
@interface Hoge : NSObject
@property (class, nonnull) NSString *classVar;
+ (NSString *) classVar;  //アクセサメソッドが必要
+ (void) setClassVar:(NSString *) value;  //アクセサメソッドが必要



@property (nonnull, readonly) NSString *readOnlyclassVar2;
+ (NSString *) readOnlyclassVar2;   //アクセサメソッドが必要、ただしreadonly

@end

Hoge.m

static NSString * classVar2 =@"yahoo.co.jp";
static NSString * readOnlyclassVar2 = @"this is what came for";

@implementation Hoge {
}

// アクセサメソッドを書いておかないと他のクラスから読めないよ
+ (NSString *) classVar{
    return classVar;
}
+ (void) setClassVar:(NSString *) value {
    classVar = value;
}

+ (NSString *) readOnlyclassVar2{
    return readOnlyclassVar2;
}
+ (NSString *) getReadOnlyClassVar2
{
    return self.readOnlyclassVar2 ; //同じクラスからアクセスする時にはこうかく。
}

@end
  • 宣言はimplementationの外にかく。その時に初期値を与えられる
  • アクセサはimplementationの中に書く。readonlyならgetterだけでおk
  • 初期値を与えられる
  • 同じクラスからもアクセスできる

MainViewController.m

他クラスから、インスタンスを作らなイでアクセスの仕方を以下に示す。

- (void)viewDidLoad {
    [super viewDidLoad];

    //インスタンスを作らずにアクセスさせるためにはこうする
    NSString *fuga = Hoge.classVar;
    NSLog(@"%@", fuga);    // => yahoo.co.jp

    // アクセサを使ってセット
    [Hoge setClassVar:@"こうやってセット"];
    NSLog(@"%@", readClassVar2);    // => こうやってセット
    
    NSString *readClassVar2 = [ClassVariableObject getReadOnlyClassVar2];
    NSLog(@"%@", readClassVar2);    // => this is what came for

}
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?