Objective-C 的成员变量和@property迷惑点 -IOS

这篇就记录一下我的迷惑点。
不讨论@property属性里的attributes到底什么功能,网上有很多,百度一下就出来了。

迷惑点:

变量声明 为啥用@property?

用@property修饰的变量,就是编译器帮我们加了get和set的方法。

那为啥要加get和set方法呢?

我个人理解这时的变量应该是private的,外部要访问这个变量,都是通过get和set的方法。

这里又说到了访问变量。

访问有的时候用点(.)有的时候用箭头(->)。用点来访问的比如test.prop这个时候用的就是get和set方法。
而用箭头(->) test->prop这个时候就是直接访问变量,如果是外部访问这就要求变量是public的了。
当没有get和set方法时也只能用箭头(->)访问。

@property声明放在哪?

放在和方法声明同级别的地方。

再贴一些网上说的东西便于理解。

OC .(点)与->(箭头)用法区别

 #import  
@interface Test : NSObject{
  int temp; //成员变量
}
@end

@implementation Test
@end 

int main(){   
    Test *t = [[Test alloc] init];  
    t->temp = 100;  
    NSLog(@"%d",t->temp);  
    return 0;
}

这里

t->temp = 100;
NSLog(@"%d",t->temp);

这两行中的t->temp会提示错误,错误说明为instance varviable “temp” is protected。说明是可以访问的,但是因为受保护所以报错,那我们把权限改成public试试。

    @public    int temp;    //成员变量

结果显示通过,没有错误,说明想法是对的。

接下来再看看.点语法

 #import  
@interface Test : NSObject{  
    int temp;   //成员变量
}@end 
@implementation Test
@end int main(){   
    Test *t = [[Test alloc] init];
  t.temp = 100;
  NSLog(@"%d",t.temp);
  return 0;
}

把代码中的t->temp改成lt.temp,发现又会报错,错误说明为Propetery temp not found。。。,也即是说没有找到temp这个属性,当然找不到,因为我们没有定义这个属性。 这时再在成员变量的声明后加一行代码

@property int temp;

代码通过,没有错误,说明.点语法是用来访问属性的。

、get方法,要是我有set、

,试试就知道

 #import  
@interface Test : NSObject{
  int temp; //成员变量
}
-(void)setTemp:(int)temp;
-(int)Temp;
@end
@implementation Test
 -(void)setTemp:(int)temp{}
-(int)Temp{}
@end 
int main(){
   Test *t = [[Test alloc] init];
  t->temp = 100;
  NSLog(@"%d",t->temp);
  return 0;
}

偷懒没有实现方法,但是同样没有报错,也就说明证实了猜想。

至此大概清楚.(点)和->(箭头)的区别了:

.(点语法)是访问类的属性,本质是调用set、get方法。

->是访问成员变量,但成员变量默认受保护,所以常常报错,手动设为public即可解决

Objective-C 成员变量

成员变量的访问权限

Objective-C中的成员变量有以下三种属性

  • public(外部及其子类可访问)
  • protected(子类可访问,外部不可访问)
  • private(外部及其子类不可访问)

默认情况下,是protected属性

例子:类A有3个属性,类B是类A的子类,main函数对于类A来说是外部。

A.h

@interface A : NSObject
{ @public
    int publicVar; @protected
    int protectedVar; @private
    int privateVar;
} 
@end

main.m

int main(int argc, const char * argv[])
{
    @autoreleasepool
    {
        A *a = [[A alloc] init];
        a->publicVar = 1;       //OK
        a->protectedVar = 2;    //Error 编译不过
        a->privateVar = 3;      //Error 编译不过
 } return 0;
}

你可能感兴趣的:(Objective-C 的成员变量和@property迷惑点 -IOS)