Objective-C

最終更新日: 2026-07-26

TOP(About this memo)) > Objective-C

参考

ブラケット記法(メッセージ式、メッセージング)

Blocks

// 宣言: 戻り値(^関数名)(引数)
void (^blocksTest1)(void);

// 代入: 関数名の後ろにイコール(=)を入れ、^(引数){}
blocksTest1 = ^(void) {
    NSLog(@"blocksTest1");
};

// 実行
blocksTest1();

// 直ぐに実行
^() {
    NSLog(@"テスト");
}();

// 宣言, 代入
void (^blocksTest2)(void) = ^(void) {
    NSLog(@"blocksTest2");
};

// 返り値あり
int (^blocksTest3)(void) = ^(void) {
    return 10;
};
void (^blocksTest5)(int x, int y) = ^(int x, int y) {
    NSLog(@"%d", x + y);
};

// 実行、NSLog()でログ出力
NSLog(@"%d", blocksTest3());

メソッドの引数がBlocks

// 「(int(^) (int a, int b))bt7」の部分が、a, bを引数にとってintを返すBlocksとなる
-(int)blocksTest7:(int(^) (int a, int b))bt7 x:(int)x y:(int)y {
    return bt7(x, y);
}
int i = [self blocksTest7:^int(int a, int b){
    return a * b;
} x:10 y:10];

@マーク

@1;     // => [NSNumber numberWithInteger:1]
@0.5;   // => [NSNumber numberWithDouble:0.5]
@YES;   // => [NSNumber numberWithBool:YES]
@"文字列" // => キャスト(?)
@[@1];  // => [NSArray arrayWithObjects:{@1} count:1]
@{@"hoge": @"fuga"}; // [NSDictionary dictionaryWithObjects:{@"fuga"} forKeys:{@"hoge"} count:1]

構造体

typedef struct Person {
    float height;
    float weight;
    int birthYear;
} Person; // struct PersonにPersonというaliasを切る。

Person a; // 変数宣言
a.height = 170.5;

クラスのヘッダファイル(.h)

@interface Person : Mammal

@protected
    // メンバ定義
    int _life;

    // なお、ここにメンバ変数を定義しなくてもよい
    // (@synthesize 時に実体となる変数を定義できるため)

// アクセサ
@property int life;
@property int lifeb;
@property int lifec;
@property int lifed;

@end

クラスの実装ファイル(.m)

#import "Person.h"
@implementation Person

// インスタンスメソッド定義
- (int)someMethod
{
    return life;
}
- (void)someMethod2:(int)xxx
{
    life += xxx;
    NSLog(@"life: %d", life);
    NSLog(@"life: %d", _life); // 直接、実体を参照しても結果は同じ。
    return;
}

// クラスメソッド定義
+ (int)someMethod3
{
    // ...
    return;
}

@synthesize life  = _life;  // 既に定義されているメンバ変数を指定
@synthesize lifeb = _lifeb; // 新しくメンバ変数を定義して指定
@synthesize lifec  = aaaa;  // 実体を指すメンバ変数の名前に決まりはない
@synthesize lifed;          // 実体を省略すると同名のメンバ変数が指定されたことになる

@end

インスタンス生成

Person *tarou = [[Person alloc] init];
// メンバセット
tarou->life = 10;
// メソッド呼び出し
[tarou someMethod];
[tarou someMethod2:5];
// クラスメソッド呼び出し
[Person someMethod3];

ラベルがついたメソッドの呼び出し例

@interface MyTest : NSObject
- (void)consoleWrightWithHeight:(NSInteger)h weight:(NSInteger)w;
@end
@implementation MyTest
- (void)consoleWrightWithHeight:(NSInteger)h weight:(NSInteger)w {
    NSLog(@"Your Height=%ld Weight=%ld", h, w);
}
@end
MyTest *test = [[MyTest alloc] init];
[test consoleWrightWithHeight:174 weight:65];
// もし、ラベルがない場合だと、以下のようになる。
// [test consoleWrightWithHeight :174 :65];