我使用以下代码...
-(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;
}
Run Code Online (Sandbox Code Playgroud)
这产生了以下两个警告......
处理这些警告是否有共同或公认的惯例?
我知道只是告诉用户他们应该在引用类成员时指定一个实例,但它很烦人.
Jus*_*tin 32
我认为这是一个相当古老的问题,并且已经接受了答案,但我有一个更好的解决方案及其代码约定.
该约定规定您使用下划线(_varName)和公共(如属性)为私有变量添加前缀,仅使用名称.
有了这个,你就可以在函数中调用相同的变量名.
例:
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
Bar*_*ark 28
不幸的是,没有没有"好"的方法来防止这个错误.常见的模式是使用一个稍微愚蠢的参数名称
-(id) initWithVariableName:(NSString*)theVariableName
withComparisonValue:(NSString*)theComparisonValue {
self.variableName = theVariableName;
self.comparisonValue = theComparisonValue;
return self;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27468 次 |
| 最近记录: |