Loose-Info.com
Last Update 2013/02/13
TOP - Objective-C - クラス - クラスメソッド

クラスメソッドは、「+」から記述が始まります。
クラスオブジェクトのメソッドとして動作します。
インスタンス変数は参照できませんが、staticで宣言した変数をクラス変数の代わりに利用できます。

+ ( 名前1 ) 名前2 ...

名前1
クラスメソッドの型名
名前2
クラスメソッド名

(例)
MyTestClass.h
#import <Foundation/Foundation.h> @interface MyTestClass : NSObject - (id)init; + (int)countInit; @end

MyTestClass.m
#import "MyTestClass.h" @implementation MyTestClass static int countInit = 0; - (id)init { if (self = [super init]) { countInit++; } return self; } + (int)countInit { return countInit; } @end

main.m
#import "MyTestClass.h" int main (void) { NSLog(@"Initialize実行後のcountInit : %d", [MyTestClass countInit]); MyTestClass *mtc1 = [[MyTestClass alloc] init]; NSLog(@"インスタンス[mtc1]作成後のcountInit : %d", [MyTestClass countInit]); MyTestClass *mtc2 = [[MyTestClass alloc] init]; NSLog(@"インスタンス[mtc2]作成後のcountInit : %d", [MyTestClass countInit]); return 0; }

実行結果
Initialize実行後のcountInit : 0 インスタンス[mtc1]作成後のcountInit : 1 インスタンス[mtc2]作成後のcountInit : 2