2013-09-27 62 views
3

由于ViewController的代码变得太大,我想知道如何将代码拆分为多个文件。这里是我遇到的问题:我们可以把IBOutlets放在一个类别中吗?

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

回答

7

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

你可以,但是,内class extension添加附加属性。 A class extension用与原始类相同的名称表示,后面跟着()。在你的代码示例,这两条线指的是@interface aViewController()实际申报class extension(不是category),无论哪个header文件的他们实际上是。

此外,你可以创建跨多个不同的页眉多级扩展。诀窍是你需要正确导入它们。

例如,让我们考虑一个名为ViewController的类。我们要创建ViewController+Private.hViewController+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文档。

+0

我不是100%确定我的原始答案,所以我查了一下,发现它不正确。我已经用正确的信息更新了答案。 :D –

+0

有趣..我总是想知道'()'是什么意思..每当我看到它在一个m文件中时,我想它只是一种私人地使用obj-c'@ property'的方式(即它会自动生成访问器..但仅限于.m文件中的访问) – abbood

+1

@abbood,是的,类扩展最常见的用途是隐藏你不想公开的变量,通常类扩展确实放在类的实现文件中。但是,嘿,你也可以这样做。 :D –

相关问题