OC基础之创建OC对象类、成员/静态变量、对象/类方法

OC 面向对象

一般需要.h 和.m(或.mm 以后不赘述) 文件配合来创建类。


.h 使用@inteface 和@end ,在之间定义,变量和方法只能定义,不能初始化

下为 Student.h

@interface Student : NSObject //@interface声明。  没有@interface  只有@implementation也能定义一个类

{

@public  //作用域  任意地方

int a;

@protected  //当前及子类

int b;

@private  //当前(包括.m)

int c;

@package //框架中都可访问,,,没用过

int d;

}

- (void) aa; //- 对象方法  调用[stu aa]

+ (void) ab; //+ 类方法    调用[Student aa] 

- (void) ac:(int)pa; //带一个int 型参数 pa    [stu ac:pa]    

- (int) ad:(int)pa  ae:(int)pb; //多个参数,可以有多个方法名   [stu ad:pa ae:pb]

+ (int) af:(int)pa:(int)pb; //多个参数,只保留第一个方法名   [stu af:pa :pb]

@end


.m 使用@implementation 和 @end, 在之间定义。 变量和方法初始化的地方

下为 Student.m

#import "Student.h" 

@implementation Student

{

int x; //这里定义的变量,没有修饰符为私有作用域。 一般也是用来定义隐藏信息的

}

- (void) aa

{

  //使用成员变量

  a = 8;

  self->c = 9; //self指代自身

}

+ (void) ab

{

  //静态方法中 不能调用成员变量

  //可以使用静态变量  

}

- (void) ac{}

- (int) ad:(int)pa  ae:(int)pb{}

+ (int) af:(int)pa:(int)pb{}

@end


静态变量

静态变量 使用的是c/c++的方式。 static 声明,只在文件oc中就是类中访问,生命周期为整个应用程序,即在下次访问时,会得到上次变化的值。

static int x;

@implementation Student

//静态变量在 对象和类方法中都可使用

- (void) test1

{

  x = 3;

}

+ (void) test2:(int)value

{

  x = value;

}

@end


main.m

#import <Foundation/Foundation.h>

int main()

{

  //初始化对象 先分配内存,再初始化

  Student* stu = [Student alloc];  //调用方法以[]

  stu = [stu init]; 


  //初始化对象 分配并初始化

  Student* stu1 = [[Student alloc] init]; 


  //初始化对象 使用[Class new] 

  Student* stu2 = [Student new]; //OC2.0语法 ,new 先分配 后会调用默认的构造方法,即init方法

  

  //调用public变量   @protected、@private、static变量在这都不可使用

  stu->a = 3; 

  NSLog(@"a-value=%d", a);  

 

  //调用对象方法

  [stu ac:3];


  //调用静态方法

  [Student af:pa:pb];


  //Class 对象

  Class stuClz1 = [Student class];

  Class stuClz2 = [stu class];

  //Class 对象调用静态方法  

  [stuClz1 ab];  


  return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值