开发者

How can I pass a property of a class as a parameter of a method in objective-c

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:

  • a CoreData managed object class MyData with dynamic properties PropA, PropB, PropC all of the same type
  • I have a utils method that will perform calculations and update one of these properties, which takes as input the MyData instance
  • how can I arrange so the utils method can accept an indication of which property to use in the calculations and updating? (e.g. PropB)

So then need:

  1. A way to pass an indication of the property to the method (e.g. send as String?)
  2. A way in the method to take this (from 1 above) and use this to both (a) access the value of this property 开发者_运维技巧in the MyData instance the method has, PLUS (b) update the property too.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜