u16suzuの blog

日々学んだことのメモブログです。

定数を static const で定義する

kは定数のプレフィックス.

// .m file

#import "ScrollButtonsView.h"

static const int kButtonNumber = 5;  
static const float kButtonPadding = 10.0f;

@implementation ScrollButtonsView
/* 省略 */
@end

文字列定数の場合は以下の通り

// .h file
#import <UIKit/UIKit.h>

extern NSString *const Notification;

@interface CustomView : UIView

@end


// .m file
#import "CustomView.h"

NSString *const Notification = @"Notification";

@implementation CustomView
@end

.h ファイルでは extern をつけて宣言することで mファイルに定義があると言うことを示している.

ステートなどはenum で定義する

#import "CustomView.h"

typedef NS_ENUM(NSInteger, HogeState) {
    HogeStateStart,
    HogeStatePause,
    HogeStateEnd
};

@implementation CustomView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        NSInteger currentState = 5;
        switch (currentState) {
            case HogeStateStart:
                break;
            case HogeStatePause:
                break;
            case HogeStateEnd:
                break;
        }

    }
    return self;
}

@end

ビットマスクの定義

typedef NS_OPTIONS(NSInteger, MyFlag) {
    MyFlagNone = 0,
    MyFlagA = 1 << 0,
    MyFlagB = 1 << 1,
};

ビットマスクを使うと MyFlagA | MyFlagB みたいな書き方ができる.