get property from id class

2020-03-28 17:50发布

问题:

ABC *abc=[ABC new];
id property=abc.property;

but:

id ClassName=NSClassFromString(ABC);
id instance=[ClassName new];

id property=???????;

i can't use instance.property,because it is id type.

i want to get a known property from (id)type class.

i try to use:

[aInstanse propertyForKey:<#(NSString *)#>];
[aInstanse propertyNamed:<#(NSString *)#>];

But Program crashes...

can you help me, thanks.

回答1:

there are many ways

you can cast it if you know the type at compile time

id property=((MyClass *)instance).myProperty;
((MyClass *)instance).myProperty = property;

or not using dot syntax

id property=[instance myProperty];
[instance setMyProperty:property];

or using valueForKey:

id property=[instance valueForKey:@"myProperty"];
[instance setValue:property forKey:@"myProperty"];


回答2:

You can just use the standard getters and setters, which default properties have and which @synthesize will create:

[instance property];
[instance setProperty:value];


回答3:

If you're sure that your class has some properties, and you know name of this properties, you can make an interface to call it. Of course, you have to cast your object to an object of this class!

Good luck!