NSNumber

NSNumber

組み込み型を NSString で取り出す

Keywords: objCType

NSNumber は C の組み込み型をラップするためのクラス。その、ラップ元の型を NSString として取り出す関数を作ってみよう。もとの型は objCType で取り出すことができる。取り出した文字列を @encode() したものと比べるんだ。

(sample)

NSString* stringOfNumber(NSNumber* number)
{
 static NSString* _b = @"BOOL";
 static NSString* _c = @"char";
 static NSString* _s = @"short";
 static NSString* _i = @"int";
 static NSString* _l = @"long";
 static NSString* _ll = @"long long";
 static NSString* _f = @"float";
 static NSString* _d = @"double";
 static NSString* _uc = @"unsigned char";
 static NSString* _us = @"unsigned short";
 static NSString* _ui = @"unsigned int";
 static NSString* _ul = @"unsigned long";
 static NSString* _ull = @"unsigned long long";

 const char* type;

 // Get Objective-C type
 type = [number objCType];
 if (strcmp(type, @encode(BOOL)) == 0) return _b;
 if (strcmp(type, @encode(char)) == 0) return _c;
 if (strcmp(type, @encode(short)) == 0) return _s;
 if (strcmp(type, @encode(int)) == 0) return _i;
 if (strcmp(type, @encode(long)) == 0) return _l;
 if (strcmp(type, @encode(long long)) == 0) return _ll;
 if (strcmp(type, @encode(float)) == 0) return _f;
 if (strcmp(type, @encode(double)) == 0) return _d;
 if (strcmp(type, @encode(unsigned char)) == 0) return _uc;
 if (strcmp(type, @encode(unsigned short)) == 0) return _us;
 if (strcmp(type, @encode(unsigned int)) == 0) return _ui;
 if (strcmp(type, @encode(unsigned long)) == 0) return _ul;
 if (strcmp(type, @encode(unsigned long long)) == 0) return _ull;
}


これで組み込み型が読みやすい形で取り出せるぜ!