类别 category VS 类扩展 extension

来源:互联网 发布:pid控制算法和图解 编辑:程序博客网 时间:2024/05/19 03:45

类别(category)

  1. Category理论上不能添加变量,但是可以使用@dynamic 来弥补这种不足。 (即运行时Runtime)
  2. 类别的方法中,不可以调用super方法。--类别的局限;

  3. category 方法可能会覆盖于同一个类class 的其它 category 中的方法。但也可能被覆盖,因为不法预知他们的加载优先顺序,出现这种情况通常会在编译时出错(如果在一个开发的SDK中使用了类别, 就最好保证类别名不同于使用者的类别名, 以及类别方法也不同于使用者的类别方法名, 通常通过加前缀来做到)

  4. 类别并不能为类声明新的实例变量,他只包含方法(并且,类别的方法优先级较高,可覆盖原类方法)。然而在类作用域内所有实例变量,都能被这些类别访问。他们包括为类声明的所有的实例变量,甚至那些被@private 修饰的变量。

  5. 我们还可以用 category里重写类原先存在的方法(但是并不推荐这么做)

  6. Even though any methods added by a category are available to all instances of the class and its subclasses, you’ll need to import the category header file in any source code file where you wish to use the additional methods, otherwise you’ll run into compiler warnings and errors.

  7. Categories can be used to declare either instance methods or class methods but are not usually suitable for declaring additional properties. It’s valid syntax to include a property declaration in a category interface, but it’s not possible to declare an additional instance variable in a category. This means the compiler won’t synthesize any instance variable, nor will it synthesize any property accessor methods. You can write your own accessor methods in the category implementation, but you won’t be able to keep track of a value for that property unless it’s already stored by the original class.

类扩展(extension)

  1. 某些情况下,我们需要声明一个@property,它对外是只读的(readonly),而对内是可读写的(readwrite),这时,可以通过Extensions实现。
  2. Unlike regular categories, a class extension can add its own properties and instance variables to a class.


0 0
原创粉丝点击