新建工程,名为:Shapes-Object,修改代码如下:
//
// main.m
// Shapes-Object
//
// Created by cloud on 13-3-7.
// Copyright (c) 2013年 cloud. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef enum {
kRedColor,
kGreenColor,
kBlueColor
} ShapeColor;
typedef struct {
int x,y,width,height;
} ShapeRect;
NSString *colorName(ShapeColor color)
{
switch (color) {
case kRedColor:
return @"red";
break;
case kGreenColor:
return @"green";
break;
case kBlueColor:
return @"blue";
break;
default:
return @"no clue";
break;
}
}
@interface Circle : NSObject
{
ShapeColor fillColor;
ShapeRect bounds;
}
- (void) setFillColor:(ShapeColor) fillColor;
- (void) setBounds:(ShapeRect) bounds;
- (void) draw;
@end
@implementation Circle
-(void) setFillColor:(ShapeColor)c
{
fillColor=c;
}
-(void) setBounds:(ShapeRect)b
{
bounds=b;
}
-(void) draw
{
NSLog(@"drawing a circle at(%d %d %d %d) in %@",bounds.x,bounds.y,bounds.width,bounds.height,colorName(fillColor));
}
@end
@interface Rectangle : NSObject
{
ShapeColor fillColor;
ShapeRect bounds;
}
- (void) setFillColor:(ShapeColor) fillColor;
- (void) setBounds:(ShapeRect) bounds;
- (void) draw;
@end
@implementation Rectangle
-(void) setFillColor:(ShapeColor)c
{
fillColor=c;
}
-(void) setBounds:(ShapeRect)b
{
bounds=b;
}
-(void) draw
{
NSLog(@"drawing a rectangle at(%d %d %d %d) in %@",bounds.x,bounds.y,bounds.width,bounds.height,colorName(fillColor));
}
@end
@interface OblateSphereoid : NSObject
{
ShapeColor fillColor;
ShapeRect bounds;
}
- (void) setFillColor:(ShapeColor) fillColor;
- (void) setBounds:(ShapeRect) bounds;
- (void) draw;
@end
@implementation OblateSphereoid
-(void) setFillColor:(ShapeColor)c
{
fillColor=c;
}
-(void) setBounds:(ShapeRect)b
{
bounds=b;
}
-(void) draw
{
NSLog(@"drawing an egg at(%d %d %d %d) in %@",bounds.x,bounds.y,bounds.width,bounds.height,colorName(fillColor));
}
@end
void drawShapes(id shapes[],int count)
{
int i;
for(i=0;i<count;i++)
{
id shape= shapes[i];
[shape draw];
}
}
int main(int argc, const char * argv[])
{
//@autoreleasepool {
id shapes[3];
ShapeRect rect0={0,0,10,30};
shapes[0]=[Circle new];
[shapes[0] setBounds:rect0];
[shapes[0] setFillColor:kRedColor];
ShapeRect rect1={30,40,50,60};
shapes[1]=[Rectangle new];
[shapes[1] setBounds:rect1];
[shapes[1] setFillColor:kGreenColor];
ShapeRect rect2={15,19,37,29};
shapes[2]=[OblateSphereoid new];
[shapes[2] setBounds:rect2];
[shapes[2] setFillColor:kBlueColor];
drawShapes(shapes, 3);
// }
return 0;
}
运行,结果如下:
如果编译报错,Worning:Must explicitly describe intended ownership of an object array parameter
需要禁用ARC
Project -> Apple LLVM compiler 3.1 - Language -> Objective-C Automatic Referencing Counting, 设置为NO即可
Objective-C 类的声明和实现,引用与C++很不一样。
@interface 类名:父类
{
变量类型 成员变量;
}
- (返回值)函数名:(参数类型)参数
@end
@implementation 类名
- (返回值)函数名:(参数类型)参数
{
函数实现
}
@end
引用
类名 c=[类名 new]
[c 成员函数:参数]