OC的基本語法
1)OC關鍵字
爲了避免與c c++ 關鍵字衝突
@class @interface @implementation @public @private @protected @try @catch @throw @finally @end @prototal @selector @synchronized @encode @defs 不明覺厲的關鍵字
2)面向對象概述
基類:NSObject
單繼承特性
接口:支持接口(協議)@protocal 接口方法可選實現 可用@protocal實現多繼承
多繼承:使用接口來實現多繼承
支持多態,支持異常處理@try @catch @finally
所有函數都是虛函數
砍掉了很多c++中複雜的語法
3)同C/C++比較
oc中,每個目標都可以表達爲id類型,可以認爲其是 NSObject * 或者 void *
nil 等同於null,表達一個目標的指針
4)類定義
OC類分爲.h文件和.m文件
.h文件存放類,函數聲明
.m文件存放類的具體實現
類聲明使用關鍵字 @interface @end來聲明
類實現使用關鍵字 @implementation @end來實現
5)對象方法和類方法
如果聲明和實現一個類的函數,需要使用 + 或者 - 用於函數的開始
+ 代表類的方法
- 代表對象的方法
6)類聲明<Dog.h> 類實現<Dog.m>舉例
//類聲明
#import <Foundation/Foundation.h>
@interface Dog: NSObject{
//寫類字段
}
//聲明類方法或對象方法
@end
//類實現
#import "Dog.h"
@implemetation Dog
@end
OC中使用import可以避免重複包含
7)創建/銷燬OC對象
創建對象 Dog *dog = [Dog alloc];
初始化構造函數 [dog init];
銷燬對象 [dog release];
8)類聲明舉例<Dog.h>
#import <Foundation/Foundation.h>
@interface Dog : NSObject{
int age;
}
-(id)init;
-(id)initWithAge:(int)newAge;
-(int)getAge;
-(void)setAge:(int)newAge;
@end
9)函數聲明及調用
OC中其實並無函數的概念,而是定義爲標籤,eg:
無參數情況: -(int)foo; 調用 int ret = [obj foo]
一個參數 : -(int)foo:(int)a; 調用 int ret = [obj foo:100]
二個參數 : -(int)foo:(int)a :(int)b;調用int ret = [obj foo:10 :20]
帶標籤形式: -(int)foo:(int)a andB:(int)b; 調用 int ret = [obj foo:100 andB:200]
舉個C/OC的例子:
//c eg. int insertObjectAtIndexBefore( Object o,int index,boolean before); int ret = obj-> insertObjectAtIndexBefore(str,2,true) //oc eg. -(int)insertObject:(NSObject *)o AtIndex:(int)index Before:(BOOL)before; int ret = [obj insertObject:10 AtIndex:2 Before:TRUE];
10)OC的重載
首先Oc不是嚴格的函數重載
@interface Foo:NSObject{ } -(int)g:(int)x; -(int)g:(float)x;//錯誤,這個方法和前一個方法衝突(因爲沒有標籤) -(int)g:(int)x :(int)y;//正確:兩個匿名的標籤 -(int)g:(int)x :(float)y;//錯誤,也是兩個匿名標籤,衝突,二選一 -(int)g:(int)x andY:(int)y;//正確:第二個標籤是andY -(int)g:(int)x andY:(float)y;//錯誤,標籤相同,衝突,同上一個,二選一 -(int)g:(int)x andAlsoY:(int)y;//正確:第二個標籤不衝突 @end