在Objective-C中,是否可以通过字符串名称检索结构属性



我有一个对象,它的属性是如下结构:

struct someStruct{
    float32 x, y;
};

我想做的是通过字符串调用该结构属性的getter:

id returnValue = [theObject performSelector:NSSelectorFromString(@"thePropertyName")];

但正如您所看到的,"performSelector:"返回的是一个对象,而不是一个结构。我尝试了我能想到的一切选角方式,但都无济于事,这让我觉得我错过了一些东西——也许是一些简单的东西。。。

有什么想法可以将returnValue哄回到结构中吗?谢谢

编辑:无论最初的回复者是谁(出于某种原因,他删除了自己的帖子(-你是对的:根据你的回答,以下内容有效:

StructType s = ((StructType(*)(id, SEL, NSString*))objc_msgSend_stret)(theObject, NSSelectorFromString(@"thePropertyName"), nil);

编辑2:关于这个问题的详细介绍可以在这里找到。

编辑3:为了对称性,以下是如何通过字符串名称设置结构属性(注意,这正是接受的答案完成设置的方式,而我的问题需要上面第一次编辑中提到的getter的方法略有不同(:

NSValue* thisVal = [NSValue valueWithBytes: &thisStruct objCType: @encode(struct StructType)];
[theObject setValue:thisVal forKey:@"thePropertyName"];

您可以使用键值编码将struct包装在NSValue中(并在返回时将其展开(来完成此操作。考虑一个具有struct属性的简单类,如下所示:

typedef struct {
    int x, y;
} TwoInts;
@interface MyClass : NSObject
@property (nonatomic) TwoInts twoInts;
@end

然后,我们可以在NSValue实例中包装和打开struct,以便将其传递给KVC方法和从KVC方法传递它。以下是使用KVC:设置结构值的示例

TwoInts twoInts;
twoInts.x = 1;
twoInts.y = 2;
NSValue *twoIntsValue = [NSValue valueWithBytes:&twoInts objCType:@encode(TwoInts)];
MyClass *myObject = [MyClass new];
[myObject setValue:twoIntsValue forKey:@"twoInts"];

要获取结构作为返回值,请使用NSValuegetValue:方法:

TwoInts returned;
NSValue *returnedValue = [myObject valueForKey:@"twoInts"];
[returnedValue getValue:&returned];

最新更新