我收到错误,myArray隐藏了一个实例变量。请简要说明错误的含义以及解决方法。谢谢你的帮助。我是使用objective-c
进行编程的新手- (IBAction)buttonPushed:(id)sender
{
NSArray *snarkyCommentArray = [[NSArray alloc] initWithObjects: @"Butter",@"Cheese",@"Gravy",@"Your fat",@"smells like roses",nil];
self.snarkOffLabel.text = [snarkyCommentArray objectAtIndex:(1)];
}
@end
答案 0 :(得分:0)
虽然代码与您的问题不符,但我仍然可以解释错误消息。
如果您的类定义了一个实例变量,然后您创建了一个具有相同名称的局部变量,编译器会警告您将使用本地变量而不是实例变量。局部变量“隐藏”实例变量。
最好确保永远不要给局部变量赋予与实例变量相同的名称,以避免混淆。通常的做法是为所有实例变量提供下划线前缀,例如_myArray
。这样,无论何时阅读代码,很明显哪些变量是实例变量,哪些变量不是。
避免此问题的另一种方法是通过self
指针引用实例变量。
假设我的类有一个名为foo
的实例变量,我有一个名为foo
的局部变量。
foo = 5; // local variable
self->foo = 10; // instance variable
答案 1 :(得分:0)
我可以说,你的ivar和local变量有相同的名字。所以你需要更改任何一个的名称。或使用箭头操作符访问您的ivar。
答案 2 :(得分:0)
请考虑以下事项:
@interface myClass : NSObject{
NSString *name;
}
- (void)print:(NSString*)name;
- (void)printName;
@end
@implementation myClass
- (void)print:(NSString*)name{
// This line will print the local variable 'name', not the instance variable 'name'
// This line will cause a warning to the effect "Local variable hides instance variable"
NSLog(@"%@", name);
}
- (void)print{
// This line will print the instance variable 'name'.
NSLog(@"%@", name);
NSString *name = @"Steve";
// This line will print the local variable 'name'.
// This line will cause a warning to the effect "Local variable hides instance variable"
NSLog(@"%@", name);
}
@end
理解实例变量和局部变量之间的区别非常重要。实例变量是在类的“@interface”部分中定义的变量。示例:
@interface myClass : NSObject {
// Instance variables
NSString *name;
float progressAmount;
NSUInteger *age;
}
@end
可以通过类的任何方法访问实例变量。局部变量是具有局部范围的变量,只能在声明它的方法或块中访问。例如:
- (int)square:(int)num{
int result = num * num;
return result;
}
在前面的示例中,num
和result
都是局部变量。 square:
方法是他们的整个世界。它们不能从square:
之外访问,也不能在square:
返回后存在。据说它们具有局部范围。
那么当实例变量和局部变量被赋予相同名称时会发生什么?这一切都归结为范围。当涉及范围时,局部变量胜过实例变量,因此当面对决定使用哪个变量时,编译器将使用局部变量。这就是编译器产生警告而不是错误的原因。发生的事情是完全可以接受的,但警告程序员仍然是一个好主意。
答案 3 :(得分:0)
您是否尝试使用NSLog
检查错误在哪里?你知道snarkyCommentArray
是否保留了你的字符串吗?检查一下
Nslog(@"snarkyCommentArray %@",snarkyCommentArray);
如果保留所有内容,那么关心您的标签,您可以在没有self
之类的情况下使用
snarkOffLabel.text = [snarkyCommentArray objectAtIndex:(1)];
如果仍然无法正常工作,请分配您的数组,如NSMutableArray
,
NSMutableArray *snarkyCommentArray = [[NSMutableArray alloc] initWithObjects: @"Butter",@"Cheese",@"Gravy",@"Your fat",@"smells like roses",nil];
希望它有所帮助。