您的位置:首页 > 编程语言 > C语言/C++

OC语言学习 (二) 创建OC对象类、成员/静态变量、对象/类方法

2014-12-09 18:45 253 查看
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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐