由于ViewController的代码变得太大,我想知道如何将代码拆分成多个文件.这是我遇到的问题: // In the original .m file, there are bunch of outlets in the interface extension.@interface aViewController()@property (
// In the original .m file, there are bunch of outlets in the interface extension. @interface aViewController() @property (weak, nonatomic) IBOutlet UIView *contentView1; @property (weak, nonatomic) IBOutlet UIView *contentView2; @property (weak, nonatomic) IBOutlet UIView *contentView3; @end
我想根据三种不同的观点将文件分成3个类别.
// In category aViewController+contentView1.m file @interface aViewController() @property (weak, nonatomic) IBOutlet UIView *contentView1; @end
但是,如果我删除了原始的contentView1插座,则它不起作用.
题
为什么我必须将contentView1插件保留在原始.m文件中?
但是,您可以在类扩展中添加其他属性.类扩展名用与原始类相同的名称表示,后跟().在你的代码示例中,引用@interface aViewController()的两行实际上都声明了一个类扩展(不是类别),而不管它们实际上在哪个头文件中.
此外,您可以跨多个不同的标头创建多个类扩展.诀窍是你需要正确导入这些.
在示例中,我们考虑一个名为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
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
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)确保每个类扩展文件导入原始类头(即ViewController.h)
2)确保类实现(即ViewController.m)文件导入每个类扩展标头.
3)确保类头(即ViewController.h)文件不导入任何类扩展头.
作为参考,您还可以在Customizing Existing Classes上查看Apple文档.