How can I pass a property of a class as a parameter of a method in objective-c?
So as an example assume I have:
So then need:
A properties will have setter and getter method. In you case, I assume there are setPropA, setPropB, setPropC for setters and PropA, PropB, PropC for getters.
Then I pass string "PropA" to util, indicate I want to access property named PropA. The util can get the value by
id val = [aObj performSelector:NSSelectorFromString(@"PropA")];
And set the property by
[aObj performSelector:NSSelectorFromString(@"SetPropA") withObject:newValue];
Or, You can pass setter and getter as parameter by NSStringFromSelector()
, turn selector into a NSString. For example, I pass setter and getter by NSDictionary.
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
NSStringFromSelector(@selector(setPropA:)), kSetterKey,
NSStringFromSelector(@selector(PropA)), kGetterKey, nil];
// inside myUtil
NSString *setter = [userInfo objectForKey:kSetterKey];
[aObj performSelector:NSSelectorFromString(setter) withObject:newValue];
NSString *getter = [userInfo objectForKey:kGetterKey];
id val = [aObj performSelector:NSSelectorFromString(getter)];
Hope this helps.
Yes, you can pass the property name as a String.
Then you can access the indicated property via Key-Value Coding: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueCoding/Articles/KeyValueCoding.html
Example:
- (void) myUtilMethod: (MyData *) myData
forPropertyNamed: (NSString *) propName /* which property to operate on (1) */
{
id oldValue = [ myData valueForKey: propName]; // get value (2a)
id newValue = ...; // your calculation here
[myData setValue: newValue forKey: propName]; // set value (2b)
}
I won't bind the 2 classes directly. You should set up a pattern design that allows you to loosely couple them together by creating a class that will do the interface between those two.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.