General Getter/Setter

Discussion in 'iOS Programming' started by yaniv92648, May 29, 2011.

  1. yaniv92648 macrumors member

    Oct 26, 2009
    In Objective-c the default getter of the property is it's name.
    if the property name is "string" then the default setter is setString.
    can i define a general getter/setter for all of the properties of a class?
    for example:
    class: Person.
    properties: NSString *ID, *name, *address.
    i want all the getter methods (ID, name, address) to return the NSString with a prefix of "A".
    the method ID will return @"AID".
    the method name will return @"Aname".
    the method address will return @"Aaddress".
    i do not want to override each getter separately because i have a lot of properties.
  2. Matthew Yohe macrumors 68020

    Oct 12, 2006
    That doesn't really make much sense. But yes, you would have to either write a getter for each one of these, or I guess just a single getter that takes an argument defining which property you want. So something like:

    [myPerson prependLetterA:@"name"];
    Then your method for this is:
    -(NSString *)prependLetterA:(NSString *)property{
    NSString *string = [self valueForKey:property];
    string = [NSString stringWithFormat:@"A%@",string];
    return string;
    But really, why are you doing this? Maybe you're doing something for some reason that you don't actually need to.
  3. yaniv92648 thread starter macrumors member

    Oct 26, 2009
    But both of this solutions are not what i want..

    Thanks 4 the reply but i don't wanna define a new method, it should be the default getter method overridden because i want everyone who calls the default properties of that class from outside will get the @"A" prefix. and i don't wanna define a specific getter 4 each property because i have many properties. i'm doing this to fix something which has been done wrong in the project, it's complicated..

    p.s. please mark the checkbox "disable smilies in text" down below in your comments, thank u.
  4. Matthew Yohe macrumors 68020

    Oct 12, 2006
    What you're asking cannot be done. There is no concept of "default getter" like you're thinking. You likely want to just change the rest of the project. I understand it might be "complicated" but the only way you can fix this is to either write out methods for every property, or change the rest of the program. And I imagine that it makes way more sense to change the program than to actually change getters to append letters. It also likely just makes sense to only change the string where it's visible to the user. So, if there's some field that displays to the user, and it should have some prepended text, then just do what I did above in that method:

Share This Page