初识Objective-C



Object-c学习总结
1.类的声明和定义

//创建类之前需要告知编译器对象的数据成员和它提供的特性,表示为新类Circle定义的接口。
@interface Circle:NSObject
{
ShapeColor fillColor;
    ShapeRect bounds;
}
//下面是三个方法声明
//先行短线,是区别于函数原型和方法声明的标记,函数原型没有先行短线
//方法声明中使用了中缀符语法技术,方法的名称及其参数是合在一起的
//可以这样调用带一个参数的方法[circle setFillColor:kRedColor]
//调用两个参数的方法 [textString setStringValue: @"hello here" color: kBuleColor];
//冒号也是名称的一部分,告诉编译器后面会出现参数
- (void) setFillColor:(ShapeColor)fillColor;
- (void) setBounds:(ShapeRect)bounds;
- (void) draw;
//告知编译器,已完成类型Circle的声明。
@end //Circle

//可以在实现中添加interface中没有声明的方法,但是这些方法都不是私有化的,
//Objective-c中不存在真正的私有方法,也无法把某个方法标识为私有方法,这是object-c动态本质的副作用。

@implementation Circle
- (void) setFillColor:(ShapeColor)c
{
    fillColor = c;
}//setFillColor

- (void) setBound: (ShapeRect) b
{
    bounds = b;
}// setBounds

- (void) draw
{
    NSLog(@"drawing a circle at(%d %d %d %d) in %@",bounbs.x,bounds.y,bounds.width,bounds.height,colorName(fillColor));
}//draw
@end //Circle
 

2.实例化对象时可以直接向类发送消息创建对象[Circle new];

3.继承中子类因逻辑需要重写父类的方法 写法如下

@implemtation Circle
- (void) setFillColor: (ShapeColor)c
{
if(c == kRedColor){
    c= kGreenColor;
    }
[super setFillColor: c];
}//setColor
@end //Circle
 

4.复合

@interface Car:NSObject
{
    Engine *engine;
    Tire *tires[4];
}
- (void) print;
@end //Circle
@implementation Car
- (void) init
{
        //如果超类可以完成所需的一次性初始化,需要调用[super init],init返回值(id型数据,即泛型对象指针)描述了初始化的对象
        //赋值的原因是防止超类在初始化过程中返回的对象不同于原先创建的对象。
      if(self = [super init]){
             engine = [Engine new];
            tires[0] = [Tire new];
            tires[1] = [Tire new];
           tires[2] = [Tire new];
           tires[3] = [Tire new];
    }
    return (self);
}//init
- (void) print{
       NSLog(@"%@",engine);
       NSLog(@"%@",tires[0]);
       NSLog(@"%@",tires[1])
       NSLog(@"%@",tires[2]);
       NSLog(@"%@",tires[3])
}//print
@end //Car
 

5.setter与getter方法
为了动态设定汽车的轮胎和引擎,可以做如下方法的更改

@interface Car: NSObject
{
Engine *engine;
Tire *tires[4];
}
//getter方法不能带有get关键字,否则通过当作参数传入的指针来返回数值。
- (Engine *) engine;
- (void) setEngine: (Engine *)newEngine;

- (Tire *) tireAtIndex: (int)index;
- (void) setTire: (Tire *) tire
            atIndex: (int)index;
- (void) print;
@end //Car;
 

使用:

- (void) setTire: (Tire *)tire
            atIndex: (int)index
{
if(index<0 || index>3){
NSLog(@"bad index (%d) in setTire:atIndex:",index);
exit(1);
    }
    tires[index] = tire;
} //setTire:AtIndex

- (Tire *) tireAtIndex: (int)index
{
if(index<0 ||index>3){
NSLog(@"bad index (%d) in setTireAtIndex:",index);
}
return tires[index];
} //tireAtIndex 
 

猜你喜欢

转载自azlove.iteye.com/blog/1675962