3

由于ViewController's 的代码变得太大,我想知道如何将代码拆分为多个文件。这是我遇到的问题:

// 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文件中?

4

1 回答 1

8

Objective-Ccategory不允许你向一个类添加额外的属性,只有方法。因此,您不能IBOutlet在 a 中添加额外的 s category。类别的表示类似于@interface aViewController (MyCategoryName)(注意括号内给出的名称)。

但是,您可以在class extension. Aclass extension用与原始类相同的名称表示,后跟()。在您的代码示例中,无论它们实际位于哪个文件中,这两行都指的是@interface aViewController()实际声明 a class extension(不是 a )。categoryheader

此外,您可以跨多个不同的标头创建多个类扩展。诀窍是您需要正确导入这些。

例如,让我们考虑一个名为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 文档。

于 2013-09-27T03:53:03.877 回答