instance variable/ method argument naming in Objective C

前端 未结 5 1076
醉话见心
醉话见心 2020-12-08 11:21

What conventions are people here following for naming of instance variables and method arguments - particularly when method arguments are used to set ivars (instance variabl

5条回答
  •  时光说笑
    2020-12-08 12:02

    As you've noted, the Cocoa style is to use method argument names like theValue if the argument name will conflict with an instance variable. There shouldn't be many times that this comes up in Objective-C 2.0 style code, however. The assumption is that you shouldn't (usually) be accessing instance variables directly. Mostly this is because doing so circumvents the Key-Value Observing machinery in Cocoa. Rather, the expectation is that you'll access and mutate properties via getter/setter methods. In Objective-C 2.0, it's easy to declare these properties and automatically @synthesize the getters/setters, so there's not much excuse for not using them. In fact, on 64-bit systems, the runtime will automatically create the instance variables for you, obviating the need to declare them and reducing the urge to use them.

    The only time you should be accessing instance variables directly is in -init and -dealloc methods:

    @interface MyObject : NSObject 
    {
      id ivar;
    }
    
    @property (retain,readwrite) id ivar; //or whatever retain/copy/assign and read/readwrite makes sense
    @end
    
    @implementation MyObject
    @synthesize ivar;
    
    - (id)initWithIvar:(id)theIvar {
      if(self = [super init]) {
        ivar = theIvar;
      }
    
      return self;
    }
    
    - (void)dealloc {
      [ivar release];
    }
    

    The reason the ivar should be used directly in these cases is beacuse the getter/setter may have side effects that depend on a fully initialized instance, thus making them dangerous in -init and -dealloc where the state of the object is fully initialized. In all other cases, you should be using self.ivar (or [self ivar] and [self setIvar:newValue]).

    It would seem that methods other than -initWithXX shouldn't have the naming conflict. If they do, shouldn't they be refactored to not have that parameter or for the Class to not have the instance variable?

    This leaves just the -initWithXX methods where you would often find a conflict between arguments and ivars. For this case, you can use any of the approaches you mention if you really can't stand the Cocoa style. Prefixing with _ works and is relatively common (I believe the @synthesize'd setters and getters will automatically do the right thing in this case, but you may have to explicitly set the _ivar as the backing).

提交回复
热议问题