60
62

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.

iOS開発でよく使うマクロ数種

Last updated at Posted at 2013-04-01

自分がアプリ開発をする際にプロジェクト問わずよく使うものをいくつか。

##型の安全なキャスト

// メッセージを続けて記述可能
// [SafeCast(NSMutableURLRequest, request) setTimeoutInterval:30];

#define SafeCast(type, var) \
    ^type *(id obj, Class clazz) {\
        if ([obj isKindOfClass:clazz]) {\
            return obj;\
        }\
        return nil;\
    } (var, [type class])

##Blocks呼び出しのnilチェックのラッパー

// 第一引数にブロック本体を、続けてブロックに渡す引数を記述
// SafeBlockHandler(completion, arg0, arg1); // == completion(arg0, arg1);

#define SafeBlockHandler(block, ...) \
    do {\
        if (block) {\
            block(__VA_ARGS__);\
        }\
    } while (0)

##NSUserDefaults読み書きのラッパー

// 実際はこのマクロを直接利用せず、型ごとにインライン関数を定義してそこから利用している
// e.g.
// static inline void NSUserDefaultsWriteObject(id aKey, id anObject)
// {
//     NSUserDefaults_Write(aKey, anObject, setObject);
// }
// static inline id NSUserDefaultsReadObject(id aKey)
// {
//     NSUserDefaults_Read(aKey, objectForKey);
// }



#define NSUserDefaults_Write(aKey, anObject, method) \
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];\
    if (anObject) {\
        [defaults method:anObject forKey:aKey];\
    } else {\
        [defaults removeObjectForKey:aKey];\
    }\
    [defaults synchronize]

#define NSUserDefaults_Read(aKey, method) \
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];\
    return [defaults method:aKey]

60
62
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
60
62

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?