一个Objective-C category
不允许额外的属性添加到一个类中,只有方法。因此,您不得在category
内添加其他IBOutlet
。类别表示类似于@interface aViewController (MyCategoryName)
(注意在括号内给出的名称)。
你可以,但是,内class extension
添加附加属性。 A class extension
用与原始类相同的名称表示,后面跟着()
。在你的代码示例,这两条线指的是@interface aViewController()
实际申报class extension
(不是category
),无论哪个header
文件的他们实际上是。
此外,你可以创建跨多个不同的页眉多级扩展。诀窍是你需要正确导入它们。
例如,让我们考虑一个名为ViewController
的类。我们要创建ViewController+Private.h
和ViewController+Private2.h
,其中有另外的privateView
网点,这些网点在ViewController.m
之内仍可访问。
下面是我们如何能做到这一点:
ViewController.h
// Nothing special here
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
// some public properties go here
@end
视图控制器+ Private.h
// Note that we import the public header file
#import "ViewController.h"
@interface ViewController()
@property (nonatomic, weak) IBOutlet UIView *privateView;
@end
视图控制器+ Private2.h
// Note again we import the public header file
#import "ViewController.h"
@interface ViewController()
@property (nonatomic, weak) IBOutlet UIView *privateView2;
@end
ViewController.m
// Here's where the magic is
// We import each of the class extensions in the implementation file
#import "ViewController.h"
#import "ViewController+Private.h"
#import "ViewController+Private2.h"
@implementation ViewController
// We can also setup a basic test to make sure it's working.
// Just also make sure your IBOutlets are actually hooked up in Interface Builder
- (void)viewDidLoad
{
[super viewDidLoad];
self.privateView.backgroundColor = [UIColor redColor];
self.privateView2.backgroundColor = [UIColor greenColor];
}
@end
这就是我们如何能做到这一点。
为什么你的代码是不工作
最有可能的,你可能混合了#import
语句。为了解决这个问题,
1)确保每个class extension
文件导入原来的类头(即ViewController.h
)
2)确保类的实现(即ViewController.m
)文件导入每个类的扩展头。
3)确保类头(即ViewController.h
)文件不进口任何类的扩展报头。
仅供参考,您还可以结帐于Customizing Existing Classes上的Apple文档。
我不是100%确定我的原始答案,所以我查了一下,发现它不正确。我已经用正确的信息更新了答案。 :D –
有趣..我总是想知道'()'是什么意思..每当我看到它在一个m文件中时,我想它只是一种私人地使用obj-c'@ property'的方式(即它会自动生成访问器..但仅限于.m文件中的访问) – abbood
@abbood,是的,类扩展最常见的用途是隐藏你不想公开的变量,通常类扩展确实放在类的实现文件中。但是,嘿,你也可以这样做。 :D –