Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Objective-C 語法:建立類別與物件

1. 建立類別

先建立一個 Single View App 模板專案,按 Command + N 新增檔案,建立名為 Student 且繼承自 NSObject 的類別,系統會產生 Student.h 與 Student.m。

Student.h 的初始內容:

#import <Foundation/Foundation.h>

@interface Student : NSObject
@end

Student.m 的初始內容:

#import "Student.h"

@implementation Student
@end

在頭檔加入成員變數與方法

#import <Foundation/Foundation.h>

@interface Student : NSObject {
    NSString *studentName;
    NSInteger age;
}
-(void) printInfo;
-(void) setStudentName: (NSString*) name;
-(void) setAge: (NSInteger) age;
-(NSString*) studentName;
-(NSInteger) age;
@end

幾個重點:@interface 是類別的起始標識(類似 Java 或 C 的 class),@end 是結束標識;繼承寫法為 Class:Parent;成員變數放在大括號之間,預設存取權限為 protected;成員方法格式為「scope (returnType) methodName: (parameterType) parameterName;」,其中類別方法用 + 開頭,實例方法用 - 開頭。

實作類別方法

#import "Student.h"

@implementation Student
-(void) printInfo {
    NSLog(@"姓名:%@ 年齡:%d歲", studentName, studentAge);
}
-(void) setStudentName: (NSString*) name {
    studentName = name;
}
-(void) setAge: (NSInteger) age {
    studentAge = age;
}
-(NSString*) studentName {
    return studentName;
}
-(NSInteger) age {
    return studentAge;
}
@end

建立並使用物件

- (void)viewDidLoad {
    [super viewDidLoad];
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    Student *student = [[Student alloc] init];
    [student setStudentName:@"張三"];
    [student setAge:10];
    [student printInfo];
    [pool release];
}

其中 [Student alloc] 呼叫類別方法配置記憶體,[object init] 則是建構子,用來初始化物件成員。執行後列印結果為:姓名:張三 年齡:10歲。

Copyright © Linux教程網 All Rights Reserved