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