Objective-C 02

来源:互联网 发布:淘宝客优惠券软件下载 编辑:程序博客网 时间:2024/04/27 23:02

1.为什么使用@class

当只是为了声明类时,为了提高效率而使用,不需要知道整个.h文件。当需要引用方法时则必须用#import directive

继承的时候需要#import ,用@class编译器会报错

2.oc的动态类型绑定是通过什么实现的

通过id实现动态绑定,id是动态类型,运行时动态绑定

id data;

Acess *a = [[Access alloc] init];

data = a;

[data print]//打印a相关的值

B *b = [[B alloc] init];

data = b;

[data print]  //打印b相关的值

3.动态类型绑定相关方法

obj isKindOfClass :object-c    表示obj 是不是objectc-c或者其子类

  if ([a isMemberOfClass:[a class]]) {  //代表的是不是自己
            NSLog(@"a is a member of ca");
        }else{
            NSLog(@"a is not a member of ca");
        }   


SEL sel = @selector(print);
        if( ![a respondsToSelector:sel]){  // 制定的selector是否响应
            NSLog(@"selector is not respond");
        }


[a performSelector:sel withObject:a withObject:ca]; //执行指定的方法,有多少参数就加多少withObject 没有就不加


4.Category的使用

类别是用来扩充原有类的功能,不能增加变量,能给原有类加方法

新建Category文件

名字随意起,下面一行是要扩展的类

然后在.h文件增加方法即可,在引用的地方引入该扩展的类既可以使用扩展的方法

category的格式:用小括号括起来

@interface NSSet (printInteger)

-(void) printSet;

@end



5.初始化一个实例


-(Numurator*)initVar{
    self = [super init];
    if(self){
        x = 20;
    }
    return self;
}


6.定义全局变量的规则

一般定义全局变量时:用小写字母g开头

7.enum类型的声明和使用 define命令 typedef命令

define:

#define M (y+3)      //注意这里没有分号
int main(int argc, const char * argv[])

{

    @autoreleasepool {
        
        int s;
        int y=3;
        s = M + 4*M;
        NSLog(@"%i",s);

}

另一种define  #define X(a) (a*a +3)   注意X后面时小括号,中括号或其他的会报错  使用的时候直接穿a的值即可,这种方式更灵活。

#if !defined (PI)
#define DOUBLEPI 3.14*2
#else
#define DOUBLEPI PI*2
#endif

typedef :理解为定义别名,让语义更清晰