八、oc中类的一些基本知识

来源:互联网 发布:php 简单工厂模式 编辑:程序博客网 时间:2024/05/01 14:24

  ------- <a href="http://www.itheima.com" target="blank">Windows Phone 7手机开发</a>、<a href="http://www.itheima.com" target="blank">.Ios培训</a>、期待与您交流! -------

     类,作为oc程序中最常见的一个单元,在程序中我们随处可见。我们可以将拥有同意性质,或者类似功能的东西归为一个类。在刚开始接触oc时,我们使用终端进行程序学习,这种情况下,需要我们自己学类的声明与实现,类的声明使用@interface  @end,类的实现使用@implementation  @end,虽然xcode会自己帮助程序员生成@end,但是建议初学者关闭代码自动生成功能,这样有助于学习。

    一般情况下,一个类都会有声明与实现,在类的声明中一般写成员变量以及类方法的声明。成员变量需要用大括号括起来,一般写在类的方法声明的前面。类的方法实现分为两种,一种是对象方法,以“-”开头,另外一种是类方法以"+"开头。

    例如:

#import<Foundation/Foundation.h>@interface colorPen : NSObject{    int _num;    int _price;}- (void)func1;+ (void)func2;@end@implementation colorPen- (void)func1{    NSLog(@"调用了ColorPen的-func1方法");   }+ (void)func2{        NSLog(@"调用了ColorPen的-func2方法");}@endint main(){    colorPen *c = [[colorPen alloc] init];    [c func1];    [colorPen func2];            return 0;}
     上面这段代码非常简单,说明了对象方法用对象去调用,注意oc中的对象全部是指针性质的。类方法用类名来调用,类名其实也是一种对象,它是一种特殊的对象,叫做类对象。

      注意:对象方法中一般不能出现[self  方法名]、[super 方法名],因为编译器,会把self当成当前对象,suepr当成父类中的对象,而类方法是是通过类名来调用的,所以这样会报错,

    例如:

#import<Foundation/Foundation.h>@interface colorPen : NSObject{    int _num;    int _price;}- (void)func1;+ (void)func2;@end@implementation colorPen- (void)func1{    NSLog(@"调用了ColorPen的-func1方法");   }+ (void)func2{        NSLog(@"调用了ColorPen的-func2方法");}@end@interface color : colorPen- (void)test1;- (void)test2;@end@implementation color- (void)test1{    [self func2]; // 尝试用self去调用类方法}- (void)test2{    [super func2]; // 尝试用super去调用类方法}@endint main(){    colorPen *c = [[colorPen alloc] init];    [c func1];    [colorPen func2];        color *c1 = [[color alloc] init];    [c1 test1];    [c1 test2];        return 0;    }
    会报一个很经典的错误:

  -[color func2]: unrecognized selector sent to instance

  意思是,发送了一个不能识别的消息给实例变量,也就是说func2方法不能直接被self与super调用。  


  函数,与方法的区别,也是初学者要注意的。函数是不依赖对象而存在的,意思就是说不能通过[方法执行者 方法]这样的方式来调用函数。例如一个函数 void num(){};那么这个函数被调用是,只需要写上num(),即可。并且函数可以写在程序的任意位置。

  

  例如:

#import<Foundation/Foundation.h>@interface colorPen : NSObject{    int _num;    int _price;}- (void)func1;+ (void)func2;@endvoid hello(){    NSLog(@"hello oc!");}@implementation colorPen- (void)func1{    NSLog(@"调用了ColorPen的-func1方法");   }+ (void)func2{        NSLog(@"调用了ColorPen的-func2方法");}@endint main(){    colorPen *c = [[colorPen alloc] init];    [c func1];    [colorPen func2];        hello(); // 函数的调用        return 0;    }

  最后,还需要注意的是,若方法是带参数的,方法名是除去-或+与返回类型以及形参后的带冒号的部分,冒号也算是方法名的一部分,同时形参不得同名,但是类方法与对象方法可以同名。

  

  例如:

 -(int)sumWithNum1:(int)num1 andNum2:(int)num2 andNum3:(int)num3

 方法名为:sumWithNum1:andNum2:andNum3:





0 0