1

iPhone / iPad开发的新手,如果这似乎是一个奇怪的问题,请原谅我。

鉴于视图中的大多数对象(或对象组)都UIViewController需要定义事件回调,将回调分组到单独的 .m 文件中,然后在视图控制器#import之后将它们分组似乎合理@implementation吗?

这样,标准方法 i nitWithNibName:-viewDidLoadshouldAutoRotateInterfaceOrientation:didReceiveMemoryWarning:-viewDidUnloaddealloc (由 Xcode 提供)将是 viewcontroller.m 文件中定义的唯一方法。viewcontroller.m 文件不会成为事件回调的庞然大物,并且更易于维护。我想你把它们放在你的@synthesize网点之后。

想法?

4

3 回答 3

0

虽然看起来您正在制作一个整体文件,但 ViewController 确实是所有这些东西的地方。如果你按照你的建议去做(这是完全可能的),你最终会得到一堆没有什么作用的文件。

在大文件中保持组织的一种方法是使用编译指示分隔方法组,如下所示:

#pragma mark lifecycle methods

-(void)dealloc{}
-(id)init{}
-(id)initWithCoder:

#pragma mark target-action

-(id)doSomethingAction:(id)sender{}
-(id)doSometingElse:(id)sender{}

Xcode 将解析编译指示并在下拉项目栏中为您分组方法以便于访问。请注意,此列表中的方法也按字母顺序列出。

于 2011-01-01T06:04:39.950 回答
0

我看到将它们分开的问题是大多数回调必须使用类局部变量,并且在您正在使用的@implementation 的相应头文件中声明它们只是更方便。对我来说,将事件处理内容保留在视图控制器中更有意义,并将任何其他功能移到某个单独的文件中......

但是任何你打破的东西也可能必须使用相同的类实例变量,这意味着你可能必须将一些类变量公开,否则你可能不会。

Justin 提出的类别突破解决了这个问题,但对我来说,使用你在技术上无法“看到”的类实例变量似乎很奇怪。

于 2011-01-01T07:09:17.263 回答
0

这是一种替代方法的图示,它使用 objc 类别:

/* File: Header A */
@interface MONViewController : NSViewController
{
    unsigned anIvar;
}

@property (nonatomic, readonly) unsigned anIvar;

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle;
- (void)dealloc;

- (void)viewDidLoad;
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation;

/* (continued) */

@end

/* File: Header A or Header B, depending on how you want to organize it */

@interface MONViewController (EventCallbacks)

- (IBAction)triviaButtonWasPressed:(id)sender;

/* (continued) */

@end

/* File: Imp A */
@implementation MONViewController

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle { /* ... */ }
- (void)dealloc { /* ... */ }
- (unsigned)anIvar { /* ... */ }

- (void)viewDidLoad { /* ... */ }
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { /* ... */ }

/* (continued) */

@end

/* File: Imp A or Imp B, depending on how you want to organize it */

@implementation MONViewController (EventCallbacks)

- (IBAction)triviaButtonWasPressed:(id)sender { /* ... */ }

/* (continued) */

@end

幸运的是,编译器会在定义类别时验证您是否定义了所有声明,就像在类中执行的那样。有些东西必须在适当的类实现中定义,例如协议。

如果您将其分成大量较小的文件,请小心 - 您的构建时间可能会受到影响。此外,在这种情况下(因为您的子类化)有些不可避免,但在这方面的可伸缩性问题应该提醒您的接口/类试图做太多事情,应该分成更小的组件。祝你好运!

于 2011-01-01T06:29:31.943 回答