get property from id class

2020-03-28 17:23发布

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.

3条回答
淡お忘
2楼-- · 2020-03-28 17:47

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

[instance property];
[instance setProperty:value];
查看更多
我想做一个坏孩纸
3楼-- · 2020-03-28 18:04

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!

查看更多
别忘想泡老子
4楼-- · 2020-03-28 18:05

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"];
查看更多
登录 后发表回答