LoginSignup
303

More than 5 years have passed since last update.

Objective-Cでよく使う便利マクロを10個集めてみた

Last updated at Posted at 2012-12-26

1. AppDelegateの参照

AppDelegate≒グローバルとして使う場合にとても便利です。
ゆとり向けです。あまり使う頻度が高いと設計ができてないということなので要注意かも。

#define APP_DELEGATE ((AppDelegate*)[[UIApplication sharedApplication] delegate])

2. テストの時に便利なBundleの参照

ユニットテストを書いてみたけどmainBundleがうまく取れなくってこける、という時のために。bundleForClass:[self class]を使うことで対応するバンドルを取得するようにします。

#define BUNDLE  [NSBundle bundleForClass:[self class]]

3. 画面サイズ

480とか320とかは今時直書きしないと思いますが^^
IB使わずに配置すると画面全体のサイズを頻繁に参照することになるので、ショートカットを定義しています。

#define SCREEN_BOUNDS   ([UIScreen mainScreen].bounds)

4. ログ出力

printfデバッグ厨には必須ですね。行数とメソッド情報加えてログ表示します。

#define LOG(A, ...) NSLog(@"DEBUG: %s:%d:%@", __PRETTY_FUNCTION__,__LINE__,[NSString stringWithFormat:A, ## __VA_ARGS__]);

5. UIColorを簡単に書く

これもIB使わない時に便利。

#define RGB(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]
#define RGBA(r, g, b, a)    [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)]

6. max, min

NSObjCRuntime.hに定義されているので個別の定義は不要ですが、地味に便利ですね。

#define MIN(a,b)    ((a) < (b) ? (a) : (b))
#define MAX(a,b)    ((a) > (b) ? (a) : (b))

7. iPhone, iPad の確認

ユニバーサルアプリを作るときにあると便利。

#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

8. Retina判定

Retina Displayを判定します。あんまり使わないかも。。

#define IS_RETINA ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [UIScreen mainScreen].scale > 1)

9. 言語取得

現在の言語を取得します。

#define LANGUAGE    ([NSLocale preferredLanguages][0])

10. よく使う標準コントロールのサイズ

UIStatusBar, UITabBar, UINavigationBar, UIToolbarの高さを定義しています。ランドスケープも対応する場合は別途調整が必要です。

#define STATUSBAR_H 20
#define TABBAR_H    48
#define NAVBAR_H    44
#define TOOLBAR_H   44

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
303