gpt4 book ai didi

防止 "local declaration hides instance variable"警告的 Objective-C 约定

转载 作者:太空狗 更新时间:2023-10-30 03:11:02 25 4
gpt4 key购买 nike

我正在使用以下代码......

-(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;
}

它产生了以下两个警告......

  • 'variableName' 的局部声明隐藏了实例变量
  • 'comparisonValue' 的局部声明隐藏了实例变量

是否有处理这些警告的通用或公认的惯例?

我明白这只是告诉用户他们应该在引用类成员时指定一个实例,但这很烦人。

最佳答案

我看到这是一个相当古老的问题,有一个公认的答案,但我有一个更好的解决方案及其代码约定。

约定规定您在私有(private)变量前加上下划线 (_varName),在公共(public)变量(如属性)前加上名称。

这样你就可以在你的函数中调用相同的变量名。

例子:

示例类.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

示例类.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

关于防止 "local declaration hides instance variable"警告的 Objective-C 约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2541716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com