2 類與對象

Objective-C 類型系統如下

這裏寫圖片描述

Class結構內容

// -------------------------------------
// CustomClass.h 接口文件內容

@interface CustomClass: NSObject

// 屬性聲明
@property int x;

// 方法聲明
- (void) mothed;

@end

// -------------------------------------
// CustomClass.m 實現文件內容

// 引入基礎類庫以及引入接口文件
#import <Fondation/Foundation.h>
#import "CustomClass.h"


@implementation CustomClass

// 接口方法的具體實現內容
- (void) mothed {

}

@end

// -------------------------------------
// 其他文件

// 聲明並創建對象: 先請求內存分配alloc,然後初始化實例對象。
CustomClass * customClass = [[CustomClass alloc] init];

// 使用類屬性
customClass.x = 10;

// 調用類方法(或者說對類發送消息)
[customClass mothed];

Struct內容

// 結構定義
typedef struct {
    int x;
} CustomStruct;

// 結構聲明: 聲明結構之後,會自動創建一個實例值。
CustomStruct customStruct;
// 結構內容使用
customStruct.x = 10;

類與結構的差別

這裏寫圖片描述

發佈了35 篇原創文章 · 獲贊 9 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章