最近在整理项目代码中key-value中的key,原来的老的代码处理的比较简单,直接使用
#define kFirstSplash @"kFirstSplash"
虽然目前这样的字符串define已经都整理到了一个文件中,但是我还是觉使用define的方式不够“面向对象”(强行找理由),另外每次定义一个key,还要专门写两遍一模一样的字符串,因此就在思考,怎么样在OC的代码中直接通过变量获取到这个变量的变量名。比如设置一个AHDatabase的类
@property (nonatomic,strong) NSString* kFirstSplash
我只要这样定义了,那么就可以通过[[AHDatabase alloc] init].kFirstSplash 获得字符串@“kFirstSplash”,其余的啥也不用做。然而始终无法解决这个问题。最终退而求其次,我找到了一个勉强可以接受的操作方式,通过[[AHDatabase alloc] init].kFirstSplash.identify这样的方式来获取字符串@“kFirstSplash”。代码如下:
AHDatabase.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface AHDatabaseUtil : NSObject
@property (nonatomic,strong) NSString* identify;
@end
@interface AHDatabase : NSObject
@property (nonatomic,strong) AHDatabaseUtil* kFirstSplashAd;
@property (nonatomic,strong) AHDatabaseUtil* kSecondSplashAd;
+(instancetype)shareInstance;
@end
NS_ASSUME_NONNULL_END
AHDatabase.m
#import "AHDatabase.h"
#import <objc/runtime.h>
@implementation AHDatabaseUtil
-(NSString *)identify{
return [self nameWithInstance:self];
}
- (NSString *)nameWithInstance:(id)instance
{
// NSTimeInterval interval = [[NSDate date] timeIntervalSince1970];
unsigned int numIvars = 0;
NSString *key=nil;
Ivar * ivars = class_copyIvarList([AHDatabase class], &numIvars);
for(int i = 0; i < numIvars; i++) {
Ivar thisIvar = ivars[i];
const char *type = ivar_getTypeEncoding(thisIvar);
NSString *stringType = [NSString stringWithCString:type encoding:NSUTF8StringEncoding];
if (![stringType hasPrefix:@"@"]) {
continue;
}
if ((object_getIvar([AHDatabase shareInstance], thisIvar) == instance)) {
key = [NSString stringWithUTF8String:ivar_getName(thisIvar)];
break;
}
}
// NSTimeInterval interval2 = [[NSDate date] timeIntervalSince1970];
//
// NSLog(@"%lf",(interval2-interval)*1000);
free(ivars);
return key;
}
@end
@implementation AHDatabase
+(instancetype)shareInstance{
static dispatch_once_t onceToken;
static AHDatabase* database = nil;
dispatch_once(&onceToken, ^{
database = [[AHDatabase alloc]init];
unsigned int numIvars = 0;
// NSTimeInterval interval = [[NSDate date] timeIntervalSince1970];
Ivar * ivars = class_copyIvarList([self class], &numIvars);
for(int i=0;i<numIvars;i++){
object_setIvar(database, ivars[i], [[AHDatabaseUtil alloc]init]);
}
// NSTimeInterval interval2 = [[NSDate date] timeIntervalSince1970];
//
// NSLog(@"%lf",(interval2-interval)*1000);
});
return database;
}
@end
以上代码可以做到只需要拷贝代码 @property (nonatomic,strong) AHDatabaseUtil* kSecondSplashAd;然后修改成自己想要的变量,就可以获取到对应的变量字符串值。即[AHDatabase ShareInstance].kSecondSplashAd.identify就是值@"_kSecondSplashAd"