歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Objective-C語法之創建類和對象

Objective-C語法之創建類和對象

日期:2017/3/1 10:18:12   编辑:Linux編程

1、創建類

1.1、新建Single View app 模版項目,按Command + N 新建文件,創建類Student ,繼承與NSObject


1.2、生成student.h 和student.m

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

1.3、在頭文件裡添加類成員變量和方法

@interface

  1. #import <Foundation/Foundation.h>
  2. @interface Student : NSObject
  3. {
  4. NSString *studentName;
  5. NSInteger age;
  6. }
  7. -(void) printInfo;
  8. -(void) setStudentName: (NSString*) name;
  9. -(void) setAge: (NSInteger) age;
  10. -(NSString*) studentName;
  11. -(NSInteger) age;
  12. @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. @implementation Student
  3. -(void) printInfo
  4. {
  5. NSLog(@"姓名:%@ 年齡:%d歲",studentName,studentAge);
  6. }
  7. -(void) setStudentName: (NSString*) name
  8. {
  9. studentName = name;
  10. }
  11. -(void) setAge: (NSInteger) age
  12. {
  13. studentAge = age;
  14. }
  15. -(NSString*) studentName
  16. {
  17. return studentName;
  18. }
  19. -(NSInteger) age
  20. {
  21. return studentAge;
  22. }
  23. @end

1.5、在View中創建並初始化,調用方法。

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

  • Sutdent *student = [[Sutdent alloc] init]; 這行代碼含有幾個重要含義
  • [Student alloc]調用Student的類方法,這類似於分配內存,
  • [object init]是構成函數調用,初始類對象的成員變量。

打印結果:
  1. 姓名:張三 年齡:10歲
Copyright © Linux教程網 All Rights Reserved