2013-01-21 40 views
3

我有有一個屬性是像下面這樣的結構的對象:在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:一個相當詳細看問題可以發現here

編輯3:爲了對稱的緣故,下面是如何通過字符串名稱來設置struct屬性(注意,這正是接受的答案完成設置的方式,而我的問題需要在第一個提到的getter編輯以上):

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

回答

4

您可以通過包裝structNSValue內(並且展開它返回時)做到這一點使用密鑰值編碼。考慮一個簡單的類與結構特性,如下圖所示:

typedef struct { 
    int x, y; 
} TwoInts; 

@interface MyClass : NSObject 

@property (nonatomic) TwoInts twoInts; 

@end 

然後我們就可以在NSValue實例包,解開了struct將它傳遞給從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]; 
+0

由於原(主要是正確的)迴應似乎已經消失在以太我接受你的答案,因爲它解決了我遇到的一個非常類似的問題。我編輯我的原始文章有我需要的具體解決方案。 –