您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 基礎知識 >> iOS 入門介紹

Objective-C 基礎入門:語法與核心概念

編輯:iOS 入門介紹

Objective-C 簡介

iOS 開發使用的是 Objective-C 語言,屬於物件導向語言。若你已有其他物件導向語言的基礎,上手會相當快。


介面與實作

在 Objective-C 中,宣告類別的檔案稱為介面檔(.h),定義實作內容的檔案稱為實作檔(.m)。

一個簡單的介面檔 MyClass.h:

 @interface MyClass:NSObject{ // 類變量聲明 } // 類屬性聲明 // 類方法和聲明 @end 

對應的 MyClass.m:

 @implementation MyClass // 類方法定義 @end 

建立物件

 MyClass *objectName = [[MyClass alloc]init] ; 

方法(Methods)

Objective-C 中方法的宣告形式:

 -(returnType)methodName:(typeName) variable1 :(typeName)variable2; 

舉個實際例子:

 -(void)calculateAreaForRectangleWithLength:(CGfloat)length andBreadth:(CGfloat)breadth; 

你可能會疑惑 andBreadth 是什麼。它其實只是一段可選的描述字串,作用是在呼叫時讓程式碼更容易讀懂。

在類別內部呼叫時寫成:

 [self calculateAreaForRectangleWithLength:30 andBreadth:20]; 

有了 andBreadth 這個字樣,一眼就能看出 20 是「寬」。而 self 表示這是自己這個類別的方法。

類別方法(Class Methods)

類別方法不需要建立物件即可直接呼叫,也不會關聯任何實例變數:

 +(void)simpleClassMethod; 

以類別名稱呼叫(假設類名為 MyClass):

 [MyClass simpleClassMethod]; 
實例方法(Instance Methods)

實例方法必須先建立物件才能呼叫,因為它會存取配置給該實例的變數:

 -(void)simpleInstanceMethod; 

建立物件後即可呼叫:

 MyClass *objectName = [[MyClass alloc]init] ; [objectName simpleInstanceMethod]; 

常用資料類型

1 NSString——字串

2 CGfloat——浮點數基本型別

3 NSInteger——整數

4 BOOL——布林值


輸出日誌

NSLog 用於印出訊息,在裝置日誌與除錯模式下的控制台都能看到:

NSLog(@"");


控制結構

除了少數補充語法,多數控制結構與 C、C++ 相同。

屬性(Properties)

屬性用於讓外部類別存取類別內的變數,例如:

@property (nonatomic, strong) NSString *myString;

存取屬性

可用點語法:

 self.myString = @"Test"; 

也可以用 setter 方法:

 [self setMyString:@"Test"]; 

類別(Categories)

類別能在不修改原始實作檔的前提下,為既有類別補上方法。MyClass 的範例:

 @interface MyClass(customAdditions) - (void)sampleCategoryMethod; @end @implementation MyClass(categoryAdditions) -(void)sampleCategoryMethod{ NSLog(@"Just a test category"); } 

陣列(Arrays)

Objective-C 提供 NSMutableArray(可變)與 NSArray(不可變)兩種陣列類別:

 NSMutableArray *aMutableArray = [[NSMutableArray alloc]init]; [aMutableArray addObject:@"firstobject"]; NSArray *aImmutableArray = [[NSArray alloc] initWithObjects:@"firstObject",nil];

字典(Dictionaries)

對應的兩種字典類別為 NSMutableDictionary(可變)與 NSDictionary(不可變):

 NSMutableDictionary*aMutableDictionary = [[NSMutableDictionary alloc]init]; [aMutableDictionary setObject:@"firstobject" forKey:@"aKey"]; NSDictionary*aImmutableDictionary= [[NSDictionary alloc]initWithObjects:[NSArray arrayWithObjects: @"firstObject",nil] forKeys:[ NSArray arrayWithObjects:@"aKey"]]; 
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved