objective-C 的代碼檔案組織

來源:互聯網
上載者:User

上一篇中,所有代碼都是放在同一個檔案main.h中的,這顯然不是一個好的方式,代碼多了以後,看著就頭大。可以將其進行拆分:

1、將所有枚舉、結構的定義單獨放在一個檔案ShapeDef.h中

//定義“幾何形狀類型”枚舉typedef enum{kCircle,kRectangle,kOblatesShperoid   } ShapeType; //定義“幾何形狀顏色”枚舉typedef enum{kRedColor,kGreenColor,kBlueColor} ShapeColor; //定義“幾何形狀矩形地區”結構typedef struct{int x,y,width,height;} ShapeRect;  //定義“幾何形狀”結構typedef struct{ShapeType type;ShapeColor fillColor;ShapeRect bounds;}Shape;

2、將所有方法都放在另一個檔案ShapeMethod.h中

#import "ShapeDef.h"//將“顏色枚舉“轉換為字串NSString *colorName(ShapeColor colorName){switch (colorName) {case kRedColor:return @"red";break;case kGreenColor:return @"green";break;case kBlueColor:return @"blue";default:return @"no clue";break;}}//畫圓void drawCircle(ShapeRect bounds,ShapeColor fillColor){NSLog(@"drawing a circle at (%d,%d,%d,%d) in %@",bounds.x,bounds.y,bounds.width,bounds.height,colorName(fillColor));}//drawCircle //畫矩形void drawRectangle(ShapeRect bounds,ShapeColor fillColor){NSLog(@"drawing a rectangle at (%d,%d,%d,%d) in %@",bounds.x,bounds.y,bounds.width,bounds.height,colorName(fillColor));}//drawRectangle //畫橢圓形void drawEgg(ShapeRect bounds,ShapeColor fillColor){NSLog(@"drawing an egg at (%d,%d,%d,%d) in %@",bounds.x,bounds.y,bounds.width,bounds.height,colorName(fillColor));}//drawEgg //畫幾何形狀void drawShapes(Shape shapes[],int count){int i;for(i=0;i<count;i++){switch (shapes[i].type) {case kCircle:drawCircle(shapes[i].bounds,shapes[i].fillColor);break;case kRectangle:drawRectangle(shapes[i].bounds,shapes[i].fillColor);break;case kOblatesShperoid:drawEgg(shapes[i].bounds,shapes[i].fillColor);break;default:break;}}}//drawShapes

3、最後在主檔案Main.m中使用ShapeMethod.h

#import "ShapeMethod.h"int main () {    Shape shapes[3]; ShapeRect rect0 ={0,0,10,30};shapes[0].type = kCircle;shapes[0].fillColor = kRedColor;shapes[0].bounds = rect0;   ShapeRect rect1 = {30,40,50,60};shapes[1].type = kRectangle;shapes[1].fillColor = kGreenColor;shapes[1].bounds = rect1; ShapeRect rect2 = {15,18,37,39};shapes[2].type = kOblatesShperoid;shapes[2].fillColor = kBlueColor;shapes[2].bounds = rect2;   drawShapes(shapes, 3);        return 0;}

註:ShapeDef.h,ShapeMethod.h,Main.m三個檔案均處於同一個項目的同一個目錄中。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.