获取以变量名作为键的 NSDictionary

Get NSDictionary with variable names as keys

假设我有 n 个变量

NSNumber* A = @(1);
NSNumber* B = @(2);
NSNumber* C = @(3);
NSNumber* D = @(4);
NSNumber* E = @(5);
...

我需要像

这样的字典
{@"A":@(1), @"B":@(2), @"C":@(3), @"D":@(4), ... }

可以想象一个更繁琐的例子,输入起来会很乏味

我好像看到过一个 C 风格的函数,但我记不起来了。类似于 NSDictionaryForVariables()

这不是一个好的方法,您可能会找到另一种方法来解决您的问题,但如果您想在这里了解您所请求的解决方案,请尝试

我们的资产

   @interface TestyViewController ()
        @property (nonatomic) NSNumber* a;
        @property (nonatomic) NSNumber* b;
        @property (nonatomic) NSNumber* c;
        @property (nonatomic) NSNumber* d;
    @end

设置值

- (void)viewDidLoad {
    [super viewDidLoad];

    self.a=@(1);
    self.b=@(2);
    self.c=@(3);
    self.d=@(4);
}

获取我们的实例变量

-(NSArray *)propertyNames{

    unsigned int propertyCount = 0;
    objc_property_t * properties = class_copyPropertyList([self class], &propertyCount);

    NSMutableArray * propertyNames = [NSMutableArray array];
    for (unsigned int i = 0; i < propertyCount; ++i) {
        objc_property_t property = properties[i];
        const char * name = property_getName(property);
        [propertyNames addObject:[NSString stringWithUTF8String:name]];
    }
    free(properties);


    return propertyNames;
  }

创建词典

- (IBAction)buttonClicked:(id)sender
{
    NSMutableDictionary *dict =  [[NSMutableDictionary alloc] init];

    for (NSString* varName in [self propertyNames])
    {
        [dict setObject:[self valueForKey:varName] forKey:varName];
    }

    NSLog(@"%@",dict);

}

结果

2015-07-15 20:30:56.546 TestC[879:27973] {
    a = 1;
    b = 2;
    c = 3;
    d = 4;
}

您要查找的 C 预处理器宏(不是函数)是 NSDictionaryOfVariableBindings。然而,在自动布局之外(而且,值得商榷的是,即使在那里),在运行时和编译时标识符之间设置依赖关系并不是一个好主意。

根据您实际要实现的目标,Key-Value Coding 可能是更好的解决方案。