Objective-C语法之创建类和对象


1、创建类

1.1、新建Single View app 模版项目,按Command + N 新建文件,创建类Student ,继承与NSObject


1.2、生成student.h  和student.m

  1. #import <Foundation/Foundation.h>   
  2.   
  3. @interface Student : NSObject  
  4.   
  5. @end  
 
  1. #import "Student.h"   
  2.   
  3. @implementation Student  
  4.   
  5. @end  

1.3、在头文件里添加类成员变量和方法

@interface

  1. #import <Foundation/Foundation.h>   
  2.   
  3. @interface Student : NSObject  
  4. {  
  5.     NSString *studentName;  
  6.     NSInteger age;  
  7. }  
  8.   
  9. -(void) printInfo;  
  10. -(void) setStudentName: (NSString*) name;  
  11. -(void) setAge: (NSInteger) age;  
  12. -(NSString*) studentName;  
  13. -(NSInteger) age;  
  14. @end  

  • @interface 类的开始的标识符号 ,好比Java  或 C 语言中的Class   
  • @end 类的结束符号
  • 继承类的方式:Class:Parent,如上代码Student:NSObject
  • 成员变量在@interface Class: Parent { .... }之间
  • 成员变量默认的访问权限是protected。
  • 类成员方法在成员变量后面,格式是:: scope (returnType) methodName: (parameter1Type) parameter1Name;
  • scope指得是类方法或实例化方法。类方法用+号开始,实例化方法用 -号开始。

1.4、实现类方法

@implementation

  1. #import "Student.h"   
  2.   
  3. @implementation Student  
  4.   
  5. -(void) printInfo  
  6. {  
  7.     NSLog(@"姓名:%@ 年龄:%d岁",studentName,studentAge);  
  8. }  
  9. -(void) setStudentName: (NSString*) name  
  10. {  
  11.     studentName = name;  
  12. }  
  13. -(void) setAge: (NSInteger) age  
  14. {  
  15.     studentAge = age;  
  16. }  
  17. -(NSString*) studentName  
  18. {  
  19.     return studentName;  
  20. }  
  21. -(NSInteger) age  
  22. {  
  23.     return studentAge;  
  24. }  
  25.   
  26. @end  

1.5、在View中创建并初始化,调用方法。

  1. - (void)viewDidLoad  
  2. {  
  3.     [super viewDidLoad];      
  4.     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
  5.       
  6.     Student *student = [[Student alloc]init];  
  7.     [student setStudentName:@"张三"];  
  8.     [student setAge:10];  
  9.     [student printInfo];  
  10.     [pool release];  
  11.   
  12. }  

  • Sutdent *student = [[Sutdent alloc] init]; 这行代码含有几个重要含义
  •  [Student alloc]调用Student的类方法,这类似于分配内存,
  •  [object init]是构成函数调用,初始类对象的成员变量。

打印结果:
  1. 姓名:张三 年龄:10岁  
  • 1
  • 2
  • 3
  • 下一页

相关内容