三大特性_封装

来源:互联网 发布:linux 创建快捷方式 编辑:程序博客网 时间:2024/06/05 15:26

学的不是代码,是思想;

用的不是代码,是思想;

比的不是代码,是思想;

一.封装:

不使用@public

set方法:

命名规范:方法名以set开头;setAge首字母大写;返回值一定是void;一定要接收一个和成员变量类型一样的参数;形参和成员变量名要不一样

声明:- (void) setAge:(int)age;实现:-(void)setAge:(int)age{if(age<=0){age=1;}_age=age;}调用:[stu setAge:10];

get方法:

命名规范:必须要有返回值且与成员变量类型一致;

方法名和成员变量一致;不用接受任何参数;

所有成员变量名都要已下划线_开头:

1.成员变量和get方法名称区分开

2.可以和局部变量区分开,带有下划线的变量,一般都是成员变量(@interface中声明的变量)。

声明:- (int)age;实现:- (int)age{return _age;}调用:[stu age];


oc弱语法:

若没有声明和实现test方法,而直接main中调用了

Person *p=[Person new];

[p test];//OC是在运行过程中才会检测对象有没有实现相应的方法

OC编译链接都没问题,执行(./a.out)报错:-[Person test]:unrecognized selector sent to instance 0x7fd2ea4097c0


类方法:

     对象方法:

——>减号  -  开头

——>只能由对象来调用

——>对象方法中能访问当前对象的成员变量(实例变量)

---- 类方法:

——>加号  -  开头

——>只能由类(名)来调用

——>类方法中不能访问成员变量(实例变量)

----类方法好处和使用场合:

——>不依赖于对象, 执行效率高

——>场合:当方法内部不需要使用成员变量时,就可以改变方式。

可以允许类方法和对象方法同名。

+ (void)printClassName;+ (void)printClassName{   }[Person printClassName];//用类名直接调用,可以提高性能

Person *p = [Person new];//对象p中有一个  isa  ,指向Person类[p printClassName];//去isa指向的类找printClassName对象方法,即以减号-开头的方法。声明:@interface Person :NSObject{ int age;}+ (void)printClassName;实现:+ (void)printClassName{//instance variable 'age' accessed in class method//实例变量age不能在类方法中访问,因为都没有创建对象,对象才有age属性,类不可能有NSLog(@"这个类叫做Person-%d",age);}- (void)test{NSLog(@"111-%d",age);}调用:[Person printClassName];

 - (void)test{[Person test]//对象方法可以调用内方法}+ (void)test{[Person test]//会引发死循环}

self:

>其实是个指针,指向调用方法的对象,即当前对象。谁调用了当前方法,self就代表谁

*self出现在对象方法中,self就代表对象

*self出现在类方法中,self就代表类

>在对象方法利用“self-> 成员变量名”访问当前对象内部的成员变量

>在对象方法或者类方法中再次调用[self 方法名];可以调用其他对象方法,或者类方法


用途一:

- (void)test{//self指向了方法调用者int _age=20;NSLog(@"",self->_age);//这个_age并不是上面刚刚定义的_age}


用途二:

实现:- (void)bark;{NSLog(@"wangwangwang");}- (void)run{[self bark];NSLog(@"runrunrun"];}调用:Dog *d=[Dog new];[d run];

用途三:

实现:+ (void)averageOfNum1:(int)num1 andNum2:(int)num2{int sum=[self sumOfNum1:num1 andNum2:num2];//self代表类return sum/2;}注意:容易引起死循环。- (void)test{ [self test];}实现:- (void)test{NSLog(@"调用了-test方法");}+ (void)test{NSLog(@"调用了+test方法");}- (void)test1{[self test];}+ (void)test2{[self test];}调用:Person *p=[Person new];————//由于p是对象,所以调用了test1,在test1中,self指的是对象,所以调用的test应该是- (void)test[p test1];//输出:调用了-test方法[Person test2];//输出:调用了+test方法
0 0