随着代码量的增加代码的可读性会越来越差,编写的难度越来越大,今天学习了多文件开发技巧,给文件分类,大大提高了代码的可读性,使代码优质化,而且利用Xcode的部分高级功能,更叫简化了代码的书写难度,提高效率
多文件开发的好处:将不同作用的代码,分散到不同的文件中,使代码结构更清晰,可读性更好
通过上一个类练习的例子介绍一下多文件的好处
首先利用Xcode创建一个项目,同时Xcode会给我们自动生成main()函数,然后在项目中创建类,同时会创建.m和.h头文件,Xcode很好的帮我们分类,
如创建Point2D类,Point2D.h文件
#import <Foundation/Foundation.h>
@interface Point2D : NSObject
{
double _x;
double _y;
}
//设置x和y的setter和getter
- (void)setX:(double)x;
- (double)x;
- (void)setY:(double)y;
- (double)y;
//设置同时设置x和y的值
- (void)setX:(double)x andY:(double)y;
//计算和其他点之间的距离
- (double)distanceWithOther:(Point2D *)other;
//计算两点之间的距离
+ (double)distancePoint:(Point2D *)p1 WithOtherPoint:(Point2D *)p2;
@end
同时会创建point2D.m文件#import "Point2D.h"
#import <math.h>
@implementation Point2D
- (void)setX:(double)x
{
_x = x;
}
- (double)x
{
return _x;
}
- (void)setY:(double)y
{
_y = y;
}
- (double)y
{
return _y;
}
//同时设置x和y的值
- (void)setX:(double)x andY:(double)y
{
[self setX:x];
[self setY:y];
}
//计算和其他点之间的距离
- (double)distanceWithOther:(Point2D *)other
{
//x的距离
double Xdistance = [self x] - [other x];
//x距离的平方
double XdisPf = pow(Xdistance, 2);
//y的距离
double Ydistance = [self y] - [other y];
//y距离的平方
double YdisPf = pow(Ydistance, 2);
//和其他点的距离
return sqrt(XdisPf + YdisPf);
}
//计算两点之间的距离
+ (double)distancePoint:(Point2D *)p1 WithOtherPoint:(Point2D *)p2
{
return [p1 distanceWithOther:p2];
}
@end
注意:创建类的时候类名要和文件名保持一致,通过文件名能知道类的作用,这样当文件很多的时候容易快速找到,Point2D.h文件中只有类的声明,Point2D.m文件中只有方法的实现,因为在不同的文件中,所以Point2D.m文件要导入Point2D.h文件。创建Cricle类也如此,所有文件同在项目文件夹下,一个项目只有一个main()函数,如下
#import <Foundation/Foundation.h>
#import "Point2D.h"
#import "Cricle.h"
int main() {
Point2D *p1 = [Point2D new];
[p1 setX:1 andY:0];
Point2D *p2 = [Point2D new];
[p2 setX:10 andY:0];
//double c = [p1 distanceWithOther:p2];
double c = [Point2D distancePoint:p1 WithOtherPoint:p2];
NSLog(@"两点之间的距离是:%.3f",c);
Cricle *c1 = [Cricle new];
[c1 setRadius:9];
[c1 setPoint:p1];
Cricle *c2 = [Cricle new];
[c2 setRadius:2];
[c2 setPoint:p2];
BOOL cc = [Cricle isIntersectionBetweenCricle:c1 andCricle:c2];
//半径之间距离
//double RandR = [c1 radius] + [c2 radius];
NSLog(@"半径之间距离是:%.3f",([c1 radius] + [c2 radius]));
if(cc)
{
NSLog(@"相交");
}
else{
NSLog(@"不相交");
}
return 0;
}
在编译的时候编译器会编译项目下的所有.m文件,这样代码结构一目了然,通过浏览项目下的文件就能知道某个文件的功能和作用。
刚刚学习多文件,还有很多需要学习,需要注意的地方,希望大家提出不足和见解