开发者

In Objective-C, how do I pass a property as an argument for a function and then call the setter/getter methods?

开发者 https://www.devze.com 2023-04-12 21:08 出处:网络
The code is probably the best way to see what I am trying to do: AcInfo.h: @interface AcInfo : NSManagedObject {

The code is probably the best way to see what I am trying to do:

AcInfo.h:

@interface AcInfo : NSManagedObject {
@private
}
@property (nonatomic, retain) NSString *registrationNumber;
@end

AcInfo.m:

@implementation AcInfo
    @dynamic registrationNumber;
@end

AnotherClass.h:

@interface AnotherClass : NSObject {
}
@property (nonatomic, retain) AcInfo               *detailItem;
@property (nonatomic, retain) IBOutlet UITextField *registrationNumberTextField;

- (void)setDetailItemValueFromUIElement:(id *)uiEl开发者_运维知识库ement forAcInfoTarget:(id *)acInfoTarget;
@end

AnotherClass.m:

@import "AcInfo.h"

@implementation AnotherClass
@synthesize detailItem, registrationNumberTextField;

- (void)viewDidLoad
{
    [super viewDidLoad];

    registrationNumberTextField.text = @"Test";
    // I expect this to set detailItem.registrationNumber to the value of
    // registrationNumberTextField.text (Test) but it doesn't change anything!
    setDetailItemValueFromUIElement:registrationNumberTextField forAcInfoTarget:detailItem.registrationNumber;
}

- (void)setDetailItemValueFromUIElement:(id *)uiElement forAcInfoTarget:(id *)acInfoTarget
{   
    if ([(id)uiElement isKindOfClass:[UITextField class]]) {
        // This doesn't do anything when it returns!
        (NSString *)acInfoTarget = (UITextField *)uiElement.text
        return;
    }
}

@end

In short, I want acInfoTarget to call the getter [detailObject registrationNumber] and the setter [detailObject setRegistrationNumber] in the setDetailItemValueFromUIElement: function...


You can set or read properties by name using

// setter
NSString *propertyName = @"myProperty";
[object setValue:newValue forKey:propertyName];

// getter
id value = [object valueForKey:propertyName];

This is slower than using the normal dot notation, though, and it's frequently (though not always) a sign of poorly-designed code.

Also note that id is a pointer type, so you probably don't actually mean "(id*)".

Your code wants to look something like this, I think:

- (void)setDetailItemValueFromUIElement:(id)uiElement forAcInfoTarget:(NSString*)acInfoTarget {
    if ([(id)uiElement isKindOfClass:[UITextField class]]) {
        NSString *newValue = ((UITextField*)uiElement).text;
        [self.detailItem setValue:newValue forKey:acInfoTarget];
    }
}


Properties are just syntax sugar for a couple of accessor methods. They are not, in essence, variables so you shouldn't treat them as such. If you want to affect a property, then what you wanting to do is call a method. So you should pass a id and selector parameter and not pointer to a variable type.

0

精彩评论

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