oc直接访问变量、间接访问变量及变量的作用域

一、点语法

(一)点语法的作用

(二)点语法的本质

如:

Stu.age=10;展开为:[stusetAge:10];

inta=stu.age;展开为:[stuage];

(三)点语法的使用注意

下面的使用方式是一个死循环:

  (1)在set方法中,self.age=age;相当于是[self setAge:age];

(2)在get方法中,return self.age;相当于是[self age];

二、变量作用域

(一)变量的作用域主要分为四种:

(2)@protected(受保护的)只能在当前类和子类的对象方法中访问

(3)@private(私有的)只能在当前类的对象方法中才能直接访问

(二)使用注意和补充

(3)一个类继承了另一个类,那么就拥有了父类的所有成员变量和方法,注意所有的成员变量它都拥有,,只是有的它不能直接访问。

例子:

#import <Foundation/Foundation.h>

@interface Person : NSObject{int _age;//默认为@protected}- (void)setAge:(int)age;- (int)age;

@end

—————————————————————————————————

#import "Person.h"@implementation Person- (void)setAge:(int)age{ _age = age;// 不能写成self.age = newAge,相当与 [self setAge:newAge];}- (int)age //get方法{ return _age;}@end

——————————————————————————————————————

#import <Foundation/Foundation.h>#import "Person.h"int main(int argc, const char * argv[]){ @autoreleasepool { // insert code here… Person *person = [[Person alloc] init]; //[person setAge:10]; person.age = 10;//点语法,等效与[person setAge:10];//这里并不是给person的属性赋值,而是调用person的setAge方法 //int age = [person age]; int age = person.age;//等效与int age = [person age] NSLog(@"age is %i", age); [person release]; } return 0;}

美文、不要轻易用过去来衡量生活的幸与不幸!

oc直接访问变量、间接访问变量及变量的作用域

相关文章:

你感兴趣的文章:

标签云: