忘備録

日々の調べ物をまとめる。アウトプットする。基本自分用。

【Objective-C】カテゴリー

カテゴリーを使ってNSDictoinaryにJavaのMap#containsKey的なメソッドを追加してみる。

NSDictionary+TestCategory.h

#import <Foundation/Foundation.h>

/**
 カテゴリの宣言には@interfaceキーワードを使います。
 クラスインターフェイスの記述に似ていますが、親クラスの指定はありません。
 代わりにカテゴリ名を括弧で囲んで指定します。
*/
@interface NSDictionary (TestCategory)

/**
 DictionaryがtestKeyをキーとした値を保持する場合にYESを返す。
 @param testKey 判定対象のキー
 @return BOOL testKeyをキーとした値を保持する場合にYES
 */
- (BOOL)containsKey:(id)testKey;

@end

NSDictionary+TestCategory.m

#import "NSDictionary+TestCategory.h"

@implementation NSDictionary (TestCategory)

- (BOOL)containsKey:(id)testKey {
    
    BOOL result = NO;
    for (id key in [self allKeys]) {
        if ([key isEqual:testKey]) {
            result = YES;
            break;
        }
    }
    return result;
}

@end

利用クラス

#import "NSDictionary+TestCategory.h"

/*----------------------------------------中略------------------------------------------*/
    
    // NSDictionaryを継承したNSMutableDictionaryでも利用可能
    NSMutableDictionary *stringKeyDic = [NSMutableDictionary dictionary];
    stringKeyDic[@"key1"] = @"value1";
    stringKeyDic[@"key2"] = @"value2";
    
    BOOL result1 = [stringKeyDic containsKey:@"key1"];
    BOOL result2 = [stringKeyDic containsKey:@"key2"];
    BOOL result3 = [stringKeyDic containsKey:@"hoge"];
    
    NSLog(@"stringKeyDic has \"key1\": %@", result1 ? @"YES" : @"NO");
    NSLog(@"stringKeyDic has \"key2\": %@", result2 ? @"YES" : @"NO");
    NSLog(@"stringKeyDic has \"hoge\": %@", result3 ? @"YES" : @"NO");

ログ出力

stringKeyDic has "key1": YES
stringKeyDic has "key2": YES
stringKeyDic has "hoge": NO

参考

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf#search='ProgrammingWithObjectiveC'