点表示法和访问实例变量

时间:2011-09-22 15:01:53

标签: iphone objective-c ipad

所以我正在阅读其他一些关于使用点符号来访问实例变量的线程,其定义如下:

  

通过self.myVariable,您正在访问实例变量myVariable   通过myVariable,您正在访问本地变量。他们不是   同样的事情。

这对我来说似乎很混乱,特别是来自java背景。有人可以清楚地向我解释一下他在本地变量的含义吗?这与在java中使用它是一回事吗?如果它是相同的那么在java中如果你说:

private int myVariable;

int testFunction(int m)
{
  myVariable = 3;
}

这将访问myVariable实例变量,因为方法中没有定义局部变量。

3 个答案:

答案 0 :(得分:2)

Self.myVariable不访问实例变量(大多数情况下不会有差异,有例外情况就像你有自定义setter一样)。相反,它访问属性的getter。它相当于:

[self myVariable];

如果您想直接访问实例变量,可以使用:

myVariable;

如果要访问另一个对象的实例变量,可以执行以下操作:

otherObject->myVariable;

虽然正如Caleb在评论中所说的那样,这是不赞成的。

答案 1 :(得分:0)

据我所知,虽然点符号只是访问事物的新方式。之前它本来是[self myVariable],现在你可以做self.myVariable。 Objective c和java之间的主要区别(至少对于这个问题)是在这个调用中如何传递值或对象

OBJECTIVE C (look at the messaging section)

JAVA

“通过self.myVariable,您正在访问实例变量myVariable,并且通过myVariable,您正在访问本地变量。它们不是一回事。” 这是有道理的,虽然我认为它的措辞很奇怪 这就是他们所说的

self.myVariable - 类的实例变量(碰巧是自己的)

myVariable - 局部变量

foo.myVariable - 类foo的实例变量

also remember "local" is the same as scope
so 
int x; //local variable to the class with a scope of the whole class

method foo{
int x; //local variable to the method with a scope of the method
}

答案 2 :(得分:0)

唔...。我不太清楚定义是在讨论什么,但局部变量肯定是在方法中定义的变量。如果您是具有实例变量的类正在访问实例变量,那么您应该直接通过它的实例变量名称直接调用它。但是,如果方法中定义了局部变量,那么它将获取局部变量而不是实例变量。

所以例如


@interface Class : NSObject
{
    int instanceVariable;
}

@end

@implementation Class

-(id)init
{
    if (self = [super init])
    {
        //You can access your instance variable like this
        instanceVariable = 1;
    }
}

@end

顺便说一句,要使用点语法,您必须实现一个访问器方法或使用@property和@synthesize。


@interface Class : NSObject
{
    int instanceVariable;
}
@property int instanceVariable;
@end

@implementation Class
@synthesize instanceVariable;

-(id)init
{
…
}
@end