2016-05-05 7 views
0

私はcar:NSObjectのようなモデルを持っていますが、それはnamecolorのようなプロパティを持っています。
今私はNSString *[email protected]"name";を持っていますが、私はこのように使うことができます[car str]? それは可能ですか?iOSのクラスプロパティ

私が試した:

objc_property_t *properties = class_copyPropertyList([_model class], &propertyCount); 

for (unsigned int i = 0; i < propertyCount; ++i) { 
    objc_property_t property = properties[i]; 
    const char * Cname = property_getName(property); 
    NSString *name = [NSString stringWithCString:Cname encoding:NSUTF8StringEncoding]; 

} 

をそれはあなたが必ずしもObjective-Cランタイムに直接飛び込む必要はありません

答えて

0

助けにはなりません。

あなたのクラスは、キーと値に準拠している場合は、そのよう-valueForKey:を使用することができます。

#import <Foundation/Foundation.h> 

// Declare the car. 
@interface Car : NSObject 

// Automatic properties are key-value compliant. 
@property (nonatomic, strong) NSString * name; 
@property (nonatomic, strong) NSString * color; 

@end 

@implementation Car 
@end 

// Entrypoint for command-line app to prove that this works 
int main(int argc, const char * argv[]) 
{ 
    @autoreleasepool 
    { 
     // First, create our car. 
     Car * car = [[Car alloc] init]; 
     car.name = @"My First Car"; 
     car.color = @"White"; 

     // Declare variables holding the names of the properties we want to access 
     NSString * nameKey = @"name"; 
     NSString * colorKey = @"color"; 

     // Retrieve the values of those properties 
     NSString * name = [car valueForKey:nameKey]; 
     NSString * color = [car valueForKey:colorKey]; 

     // Do something with the result. 
     NSLog(@"My car '%@' is '%@'.", name, color); 
    } 

    return 0; 
} 
+0

おかげで、 。 –

0

はい。 (それはオブジェクトポインタを取り、オブジェクトポインタを返すメソッドなので)[car name][car performSelector:@selector(name)]として行うことができ、そしてあなたは、文字列から動的セレクタを提供したい場合は、あなたが行うことができます:それは動作します

NSString *str = @"name"; 
NSString *name = [car performSelector:NSSelectorFromString(str)]; 
関連する問題