首页 > 其他分享 >[第四篇]object c的访问权限和调用方法.

[第四篇]object c的访问权限和调用方法.

时间:2022-11-24 11:36:55浏览次数:41  
标签:name int age object teacher void 第四篇 权限 self


  1. 公开的对象字段访问 在外部调用使用​​obj->field​​ 如
@public
int publicField;
  1. 默认的访问权限为​​protected​​只有自身和子类才可以访问,外部无法访问.
  2. 设置权限在要加的字段 上面加上类似java一样的注解如​​@public​
  3. 如果不写声明直接写实现,则代表是私有方法.只有类本身能访问,其它类无法访问,
  4. 访问权限修饰符只能作用在字段上.
  5. 静态字段 的定义用​​static​​ ,但是和c意义,没有类的概念,只有访问的控制概念,也就是同一个文件只能访问这个,要实现让其它文件访问,那么可以间接的提供方法来操作.
  6. 静态字段只能放到.m文件中,否则出错.
  7. object c的静态方法体里面也可以通过​​self​​访问自身,或者父类公开的静态方法.
  8. 和其它编程语言不通,object c静态方法也区分私有和公开,如果是私有的,则子类无法调用​​[self ]​​访问自己的静态方法

撸代码

声明文件

#import <Foundation/Foundation.h>

@interface Teacher : NSObject
{
int _age;
NSString *_name;
long _birthday;
@private
int privaeteField;
int defaultField;
@public
int publicField;



}
-(void)setAge:(int) age;// 相对于java的setAge(int age);
-(int)age;//getAge();
-(NSString *) name;
-(void)setName:(NSString *) name;
-(long)getBirthdayxx;
-(id)initWithNoAndName:(int )age teacherName :(NSString *) name;
-(void)publicobjecthello;
+(void)publichello;

@end

实现文件

//

#import "Teacher.h"

@implementation Teacher //实现文件不需要用大括号包裹起来.
static int staticPublicField;

-(void)setAge:(int)age{

_age=age;
// self.age=age;//死循环 因为.语法实际上就是调用setAGE
}
// (void)setAge:(int) age{
// _age=age;
// }
// 相对于java的setAge(int age);
-(int)age{
// return self.age;//调用的就是 getAge()方法,也就是本方法,也是死循环.
// return [self age];//也是死循环,调用的依然是方法.
return _age;
}//getAge();

-(long)getBirthdayxx{
return [self age]+30;
}

-(NSString *)name{
return _name;
}

-(id)initWithNoAndName:(int)age teacherName:(NSString *)name{
if(self=[super init]){
self.age=age;
self.name=name;
}
return self;

}

-(void)setName:(NSString *)name{
_name=name;
}

-(NSString *)description{
NSString *str =[NSString stringWithFormat:@"age %d , super class name %@ ,name %@",self.age,[super description],self.name];
return str;
}

-(void)publicobjecthello{
NSLog(@"公开的对象方法被调用");
[self privateobjecthello];
}

-(void)privateobjecthello{
NSLog(@"私有的对象方法被调用");
}

+(void)publichello{
NSLog(@"公开的静态方法被调用,因为我写了声明文件 ");
[self privatemethod];
}
+(void)privatemethod{
staticPublicField++;
NSLog(@" 私有的静态方法被调用,因为我没有写声明文件");
}

@end

用例局部代码

Teacher *teacher=[[Teacher alloc] initWithNoAndName:60 teacherName:@"qssq"];
teacher.age=30;
[teacher setAge:teacher.age+10];
NSLog(@"teacher age %d , age %d ,birthday %ld name is %@ obj : %@",teacher.age ,[teacher age],[teacher getBirthdayxx],[teacher name],teacher);
// [teacher hello];
teacher->publicField=10;
[teacher publicobjecthello];




[第四篇]object c的访问权限和调用方法._封装


image.png


番外篇

xcode 9.2创建object c class的快捷方法.



[第四篇]object c的访问权限和调用方法._java_02


image.png

标签:name,int,age,object,teacher,void,第四篇,权限,self
From: https://blog.51cto.com/u_15458814/5882959

相关文章