O-C简介
O-C是C语言的面向对象的一个超集。
O-C关键字
为避免和已有的C、C++关键字冲突,O-C关键字都以@开始。
常用关键字:@class,@interface,@implementation,@public,@private,@protected,@try,@cathc,@throw,@finally,
@end,@protocol,@selector,@synchronized,@encode,@defs
O-C与C语言对比
| C | O-C |
基本类型 | Char,short,int,long long,BOOL | |
布尔 | TRUE,FALSE | YES,NO |
基本语句 | If else switch for while do goto | |
for扩展 |
| For (xx in xx) |
类似泛型 | void * | id(NSObject *或void *) |
空值 | null | nil |
函数 |
| 全部函数都是public,使用@categories实现函数私有化 |
O-C与C函数对比
| O-C | C |
无参数 | -(int)foo; int ret=[obj foo]; | int foo(); int ret=obj->foo(); |
一个参数 | -(int)foo:(int) a; int ret=[obj foo:10]; | int foo(int a); int ret=obj->foo(10); |
两个参数 | -(int)foo:(int)a :(int)b; int ret=[obj foo:10 :20]; | int foo(int a,int b); int ret=obj->foo(10,20); |
带标签 | -(int)foo:(int)a andB:(int)b; int ret=[obj foo:10 andB:20]; | int fooandB(int a,int b); int ret=obj->foo(10,20); |
O-C对象
基类 | NSObject |
单继承 | 是单继承 |
接口 | 支持,使用协议@protocol,协议方法可选实现 |
多继承 | 使用接口来实现多继承 |
多态 | 支持多态 |
抽象类 | 支持抽象类 |
异常处理 | 简单异常处理@try @catch @finally |
虚函数 | 所有函数都是虚函数 |
类定义
类分为2个文件,一个是.h,另一个是.m
.h存放类与函数的声明,使用关键字@interface@end
.m存放类与函数的实现,使用关键字@implementation@end
函数需要使用+或-开始,+表示类的方法,-表示对象的方法
实例
类声明
#import <Foundation/Foundation.h>
@interface Dog : NSObject
{
@protected
int ID;
@public
int age;
@private
float price;
}
-(id) init;
-(id) initWithID:(int)newID;
-(id) initWithID:(int)newID andAge:(int)newAge;
-(void) setAge:(int)newAge;
-(int) getAge;
//@property(assign) int age;//等同于上两行
//@property float price;//等同于下两行
//属性补充:
//readwrite(缺省),readonly
//assign(缺省),retain,copy
//nonatomic表示不用考虑线程安全问题
//getter=...,setter=...重设函数名
-(void) setPrice:(float)newPrice;
-(float) getPrice;
-(void) dealloc;
@end
类实现
#import “Dog.h”
@implementation Dog
-(id) init;
{
return [self initWithID:1];
}
-(id) initWithID:(int)newID;
{
return [self initWithID:newID andAge:10];
}
-(id) initWithID:(int)newID andAge:(int)newAge
{
self=[super init];
If(self){
ID=newID;
age=newAge;
price=100.0f;
}
return self;
}
//@synthesize age;//等同于下面getter和setter函数的实现
-(void) setAge:(int)newAge
{
Age=newAge;
}
-(int) getAge
{
return age;
}
//@synthesize price;//等同于下面getter和setter函数的实现
-(void) setPrice:(float)newPrice
{
price=newPrice;
}
-(float) getPrice
{
return price;
}
-(void) dealloc
{
NSLog(@"is dealloc");
[super dealloc];
}
@end
主函数
#import <Foundation/Foundation.h>
#import “Dog.h”
int mian(int argc,const char * argcv[])
{
//NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
@autoreleasepool{
NSLog(@”Hello,world!”);
//Dog *dog1=[[Dog alloc] init] autorelease];
Dog *dog1=[Dog alloc] init];
int ID=[dog1 getID];
printf(“dog1 id is %d”,ID);
[dog1 release];
}
//[pool release];
retrun 0;
}