Objective-C 熟记小概念

1.定义类: 在.h文件中,

          @interface 类名:父类名

          {

       成员变量;

          }

     成员函数;

     @end;

          在.m文件中,

          @implementation 类名

          成员函数定义;

          @end;

2.成员函数定义:-(返回值类型)函数名:(参数类型)参数,...

         -(void) setColor:(NSString*)newColor

          {

             Color=newColor;

          }    

          -(void) setNumber:(int)newNumber

          {

             Number=newNumber;

          }

3.实例化类:

          myCar=[Car new];

          [myCar setColor:red];

          [myCar setNumber:Num];

4. @class指令:

   当一个类中要使用另一个已经定义好的类时,用@class,若要用到其中的方法,则要#import这个类。

5.内存管理:

   iphone操作系统不支持垃圾回收机制。

   创建一个对象一般用alloc+init,也可用new;

  alloc,copy,retain,release,autorelease;

6.Foundation框架:

   @import <Foundation/Foundation.h>

   NSString类,NSMutableString类;

   NSArray类,NSMutableArray类;

   NSDictionary类,NSMutableDictionary类;

7.存取器:

  声明类变量时,可使其成为属性。@property int Number;

  .m文件中,可加入@synthesize Number,自动生成setter和getter方法;

  这样,便可用点操作符访问成员变量,car.Number=27;

8.创建对象:

  id 对象名=[类名 alloc];

  [对象名 init];

 Boat *boat=[[Boat allco] init];

  Boat *boat=[[Boat alloc] initWithNum:123

                           Color:@"red"];

  一般情况下,init时这样写:

  -init

  {

        if(self=[super init]){

          //初始化操作

        return self;

  }

  有参数时,

  -(id) initWithNum:(int) Num

        Color:(NSString*) Color;

9.变量作用域:

  没有任何作用域限制时,默认为protected;

10. @try异常处理:

  @try{}

  @catch(NSException *exception){NSLog(@"Catch exception name :%@; reason:%@;",

                                [exception name],[exception reason]);}

  @finally{}

11.类目与协议:

   有时候需要在一个已经定义好的类中加入一些方法而不重写该类,可以使用类目(categories)。

   如已定义一Circle类,CircleCal.h文件中,

   @import "Circle.h"

   @interface Circle(CircleCal)

   -(float) AreaCal;

   -(float) LenCal;

   @end;

   CircleCal.m文件中,

   #import "CircleCal.h"

   @implementation Circle(CircleCal)

   -(float) AreaCal{}

   -(float) LenCal{}

   @end;

   此时便可在main函数中调用新定义的函数;

   ps:类目不能向类中添加实例变量;类目可以覆盖它所要扩展的类中的方法,不过应尽量避免;使用类目对一个类进行扩展时,同样会影响到该类的子类。

   协议是一个方法列表。它声明了一系列方法而不予以实现。协议不是类本身,没有父类,而且不能定义成员变量。

   @protocol Calculating

   -(void) CalculateArea;

   @end;

   @interface Rectangle:NSObject <Calculating>{}

   在定义Rectangle中的成员函数时,也要定义Calculating中的方法,这样才能调用。

   @protocol有两个修饰符:@optional和@required,

   被@optional修饰的方法,在采用该协议的类中可以选择不实现,而采用@required修饰的方法,则必须实现。默认为@required。

posted @ 2011-08-03 14:59  程序是啥  阅读(294)  评论(0编辑  收藏  举报