ios developer tiny share-20160921

来源:互联网 发布:淘宝公示30天是啥用途 编辑:程序博客网 时间:2024/06/07 04:08

今天详细讲下Objective-C中extension和category的区别


Class Extensions Extend the Internal Implementation

A class extension bears some similarity to a category, but it can only be added to a class for which you have the source code at compile time (the class is compiled at the same time as the class extension). The methods declared by a class extension are implemented in the @implementation block for the original class so you can’t, for example, declare a class extension on a framework class, such as a Cocoa or Cocoa Touch class like NSString.

The syntax to declare a class extension is similar to the syntax for a category, and looks like this:

@interface ClassName () @end

Because no name is given in the parentheses, class extensions are often referred to as anonymous categories.

Unlike regular categories, a class extension can add its own properties and instance variables to a class. If you declare a property in a class extension, like this:

@interface XYZPerson ()@property NSObject *extraProperty;@end

the compiler will automatically synthesize the relevant accessor methods, as well as an instance variable, inside the primary class implementation.

If you add any methods in a class extension, these must be implemented in the primary implementation for the class.

It’s also possible to use a class extension to add custom instance variables. These are declared inside braces in the class extension interface:

@interface XYZPerson () {    id _someCustomInstanceVariable;}...@end


0 0
原创粉丝点击