Objective-C程式設計語言的主要目的是為C程式設計語言新增物件導向,類是Objective-C的核心特性,支援物件導向程式設計,通常稱為使用者定義型別。
類用於指定物件的形式,它將資料表示和方法組合在一起,以便將資料操作到一個整齊的包中。 類中的資料和方法稱為類的成員。
@interface
和@implementation
。定義類時,可以為資料型別定義藍圖(或模板)。 但實際上並沒有定義任何資料,但它確實定義了類名的含義,即類的物件將包含什麼以及可以對這樣的物件執行什麼操作。
類定義以關鍵字@interface
開頭,後跟介面(類)名稱; 和一個由一對花括號括起來的類體。 在Objective-C中,所有類都派生自名為NSObject
的基礎類別。 它是所有Objective-C類的超類。 它提供了記憶體分配和初始化等基本方法。 例如,使用關鍵字class
定義Box
類,如下所示 -
@interface Box:NSObject {
//範例變數
double length; // Length of a box
double breadth; // Breadth of a box
}
@property(nonatomic, readwrite) double height; // Property
@end
範例變數是私有的,只能在類實現中存取。
類提供物件的藍圖,因此基本上是從類建立物件。宣告一個類的物件與宣告基本型別變數的宣告完全相同。以下語句宣告了Box
類的兩個物件 -
Box box1 = [[Box alloc]init]; // Create box1 object of type Box
Box box2 = [[Box alloc]init]; // Create box2 object of type Box
box1
和box2
這兩個物件都有自己的資料成員副本。
使用成員存取運算子(.
)存取類物件的屬性。嘗試下面的例子來理解 -
#import <Foundation/Foundation.h>
@interface Box:NSObject {
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
}
@property(nonatomic, readwrite) double height; // Property
-(double) volume;
@end
@implementation Box
@synthesize height;
-(id)init {
self = [super init];
length = 1.0;
breadth = 1.0;
return self;
}
-(double) volume {
return length*breadth*height;
}
@end
int main() {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Box *box1 = [[Box alloc]init]; // Create box1 object of type Box
Box *box2 = [[Box alloc]init]; // Create box2 object of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 分配值
box1.height = 15.0;
// box 2 分配值
box2.height = 20.0;
// volume of box 1
volume = [box1 volume];
NSLog(@"Volume of Box1 : %f", volume);
// volume of box 2
volume = [box2 volume];
NSLog(@"Volume of Box2 : %f", volume);
[pool drain];
return 0;
}
執行上面範例程式碼,得到以下結果:
$main
2018-11-16 01:29:42.781 main[106799] Volume of Box1 : 15.000000
2018-11-16 01:29:42.782 main[106799] Volume of Box2 : 20.000000
在Objective-C中引入了屬性,以確保可以在類外部存取類的範例變數。
各部分屬性宣告如下 -
@property
開頭,它是一個關鍵字strong
,unsafe_unretained
或weak
。 類似地,對於其他型別,可以使用readwrite
或readonly
。synthesize
語句。 但是在最新的XCode
中,合成部分由XCode
處理,不需要包含synthesize
語句。只有屬性才能存取類的範例變數。 實際上,為屬性建立了內部getter
和setter
方法。
例如,假設有一個屬性@property(nonatomic,readonly)BOOL isDone
。 建立了setter
和getter
,如下所示。
-(void)setIsDone(BOOL)isDone;
-(BOOL)isDone;