iOS Dev (16) 一些 OC 的基础知识点小节之一

来源:互联网 发布:包小三选股软件 编辑:程序博客网 时间:2024/05/29 19:29

iOS Dev (16) 一些 OC 的基础知识点小节之一

  • 作者:CSDN 大锐哥
  • 博客:http://blog.csdn.net/prevention

1 静态方法中的 self

在静态方法(类方法)中使用 self ,self 表示这个类。比如以下两个方法的意思是一样的:

    + (void) wtf    {        [self alloc];    }    + (void) wtf    {        [ClassName alloc];    }

2 点号的真正含义

OC 中一个对象后面用“.”后面再带一堆东西,表示 get 方法或 set 方法,而不是指成员变量。至于是 get 还是 set 取决于应用场景是需要返回值还是不需要返回值的 void 。所以有:

    [[UIViewController alloc] init]; 其实可以写成 UIViewController.alloc.init;

3 私有方法

OC 在 .m 中实现的方法,而不在 .h 中使用的方法,都是私有方法。

4 成员变量的默认作用域

与 C++ 一样,有三种作用域:

  • public
  • protected
  • private

OC 在 .h 中声明的成员变量,默认都是 protected。比如:

@interface ClassName: NSObject{    int _age;    int _sex;}@end

以上的 age 和 sex 都是 protected 的,即可以在该类和子类中访问。

4 如何指定成员变量的作用域?

直接上代码吧:

@interface ClassName: NSObject{    @public    int _age;    @private    int _sex;   }@end

5 get 方法和 set 方法的正规写法

@interface ClassName: NSObject{    int _age;    int _sex;}- (int) age;- (void) setAge:(int)age;@end

6 写个构造方法

有两种写法,注意第一种中是有 * 的,表示指针。

- (ClassName *)initWithArg:(int)arg{}

也可以用 id 哦~

- (id)initWithArg:(int)arg{}

7 继承后调用父类的构造方法

- (id)initWithArg:(int)arg{    if (self = [super init])    {        _arg = arg;    }    return self;}

8 [[Blabla alloc] init] 的简单写法

ClassName *cn = [[ClassName alloc] init];ClassName *bn = [ClassName new]; // 不建议使用

-

转载请注明来自:http://blog.csdn.net/prevention

1 0