Objective-Ccategory
不允许你向一个类添加额外的属性,只有方法。因此,您不能IBOutlet
在 a 中添加额外的 s category
。类别的表示类似于@interface aViewController (MyCategoryName)
(注意括号内给出的名称)。
但是,您可以在class extension
. Aclass extension
用与原始类相同的名称表示,后跟()
。在您的代码示例中,无论它们实际位于哪个文件中,这两行都指的是@interface aViewController()
实际声明 a class extension
(不是 a )。category
header
此外,您可以跨多个不同的标头创建多个类扩展。诀窍是您需要正确导入这些。
例如,让我们考虑一个名为ViewController
. 我们想要创建ViewController+Private.h
并且ViewController+Private2.h
有额外的privateView
网点,这些网点仍然可以在ViewController.m
.
我们可以这样做:
视图控制器.h
// Nothing special here
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
// some public properties go here
@end
ViewController+Private.h
// Note that we import the public header file
#import "ViewController.h"
@interface ViewController()
@property (nonatomic, weak) IBOutlet UIView *privateView;
@end
ViewController+Private2.h
// Note again we import the public header file
#import "ViewController.h"
@interface ViewController()
@property (nonatomic, weak) IBOutlet UIView *privateView2;
@end
视图控制器.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
)不导入任何类扩展头文件。
作为参考,您还可以查看有关自定义现有类的 Apple 文档。