各种类型的数据转换字符串太麻烦了,有没有好的方法方式
解决方案
OC里没有像C++那种重载的概念,但是有个宏可以实现类似的功能__attribute__((overloadable))
可以建一个文件类似ConvertToNSString.h,在放入以下代码即可实现一个方法转换任意类型的功能。
#ifdef __OBJC__
#import
#endif
#if __has_extension(attribute_overloadable)
staticinline__attribute__((overloadable)) NSString* stringFrom(idarg) {
return[NSStringstringWithFormat:@"%@", arg];
}
staticinline__attribute__((overloadable)) NSString* stringFrom(chararg) {
return[NSStringstringWithFormat:@"%c", arg];
}
staticinline__attribute__((overloadable)) NSString* stringFrom(unsignedchararg) {
return[NSStringstringWithFormat:@"%c", arg];
}
staticinline__attribute__((overloadable)) NSString* stringFrom(shortarg) {
return[NSStringstringWithFormat:@"%hd", arg];
}
staticinline__attribute__((overloadable)) NSString* stringFrom(unsignedshortarg) {
return[NSStringstringWithFormat:@"%hu", arg];
}
staticinline__attribute__((overloadable)) NSString* stringFrom(intarg) {
return[NSStringstringWithFormat:@"%d", arg];
}
staticinline__attribute__((overloadable)) NSString* stringFrom(unsignedintarg) {
return[NSStringstringWithFormat:@"%u", arg];
}
staticinline__attribute__((overloadable)) NSString* stringFrom(longarg) {
return[NSStringstringWithFormat:@"%ld", arg];
}
staticinline__attribute__((overloadable)) NSString* stringFrom(unsignedlongarg) {
return[NSStringstringWithFormat:@"%lu", arg];
}
staticinline__attribute__((overloadable)) NSString* stringFrom(longlongarg) {
return[NSStringstringWithFormat:@"%lld", arg];
}
staticinline__attribute__((overloadable)) NSString* stringFrom(unsignedlonglongarg) {
return[NSStringstringWithFormat:@"%llu", arg];
}
staticinline__attribute__((overloadable)) NSString* stringFrom(floatarg) {
return[NSStringstringWithFormat:@"%f", arg];
}
staticinline__attribute__((overloadable)) NSString* stringFrom(doublearg) {
return[NSStringstringWithFormat:@"%f", arg];
}
#endif