I am using the following code ...
-(id) initWithVariableName:(NSString*)variableName withComparisonValue:(NSString*)comparisonValue {
// super init
self = [super init];
if (!self) return nil;
// set instance variables
self.mustExist = NO;
self.reverseCondition = NO;
self.regularExpression = NO;
self.variableName = variableName; // generates warning
self.comparisonValue = comparisonValue; // generates warning
return self;
}
which generated the following two warnings ...
Is there a common or accepted convention for dealing with these warnings?
I understand that it is simply to inform the user that they should specify an instance when referring to the class member, but its annoying.
I see this is a fairly old question with a accepted answer but I have a better solution and its code convention.
The convention states that you prefix private variables with a underscore (_varName) and public (like properties) with just the name.
With this you just can call the same variable name in your functions.
Example:
ExampleClass.h
@interface ExampleClass : NSObject
{
NSString *_varName; //this is not required if you create a property
}
@property (nonatomic, retain) NSString *varName;
- (void)someMethodWithVarName:(NSString *)varName;
@end
ExampleClass.m
#import "ExampleClass.h"
@implementation ExampleClass
@synthesize varName = _varName; //if you don't declare the _varName in the header file, Objective-C does it for you.
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
- (void)someMethodWithVarName:(NSString *)varName
{
_varName = varName; //just for example purpose
}
@end
Unfortunately, no there's no "good" way to prevent this error. The common pattern is to use a slightly stupid parameter name like
-(id) initWithVariableName:(NSString*)theVariableName
withComparisonValue:(NSString*)theComparisonValue {
self.variableName = theVariableName;
self.comparisonValue = theComparisonValue;
return self;
}
If your method truly is an initialiser, don't forget to do your self = [super init];
.
- (id) initWith...
{
self = [super init];
if (!self) return nil;
// do stuff
return self;
}
I have never personally encountered a situation where self
has changed to nil
or another value, but it's the Objective-C Initialiser Idiom™.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With