Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

reflection - Access Objective-C property dynamically using the name of the property

I know the string name of a property of an object. How would I go about getting and setting that property using the string?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

While @weichsel is correct, there is a better way.

Use:

[anObject valueForKey: @"propertyName"];

and

[anObject setValue:value forKey:@"propertyName"];

Obviously, @"propertyName" can be an NSString that is dynamically composed at runtime.

This technique is called Key Value Coding and is fundamental to Cocoa.

Why this is better is because -valueForKey will do what is necessary to "box" whatever type the property returns into an object. Thus, if the property is of type int, it'll return an NSNumber instance containing the int.

This is much easier to deal with -- performSelector will only work for types that happen to fit into a pointer's worth of memory.

Note that there is also -setValue:forKey:.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...