2011-08-08 19 views
1

我需要为我的所有UIViewControllers附加一个方法。该方法只是返回一个指向我的主应用程序委托类对象的指针。但是,xcode 4在声明输出参数类型为MyAppDelegate的头文件中引发错误“解析期望的类型”。如果我将其更改为其他类型,例如id,则错误消失。但是我使用点语法来访问主应用程序委托属性,如果我将该类型更改为ID,则xcode4无法识别我的主应用程序委托属性。我已经将类的定义文件包含到了我访问此方法的那些UIViewController类文件中。这里是我的类定义:访问链式方法时,类别是否允许使用点语法?

#import <Foundation/Foundation.h> 
#import <UIKit/UIKit.h> 
#import "MyAppDelegate.h" 

@interface UIViewController (MyCategory) 

-(MyAppDelegate *) appDelegate; // xcode 4 complains about MyAppDelegate type, though it autocompletes it and show even in green color. 

@end 

这里是一个实现:

#import "MyCategory.h" 

@implementation UIViewController (MyCategory) 

-(MyAppDelegate *)appDelegate{ 
    MyAppDelegate *delegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate]; 
    return delegate; 
} 

编辑:为什么我采取这一类的原因是,我需要有方便快捷的访问我的主要的应用程序从代码的任何地方委托(在我的情况下,从UIViewControler对象):

// handy shortcut :) 
self.appDelegate.someMethod; 

//not so handy shortcut :(
MyAppDelegate *delegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate]; 
+1

如何声明MyAppDelegate? –

+0

@interface MyAppDelegate:NSObject 。它只是实现UIApplicationDelegate协议。 – Centurion

+0

然后尝试'id delegate = ...'来代替。 –

回答

1

我认为你的头文件中有一个依赖周期。如果MyAppDelegate.h直接或间接导入MyCategory.h,则第一次编译类别声明时,编译器将不知道MyAppDelegate是什么。你应该从MyCategory.h头去除MyAppDelegate.h进口和使用正向类声明替换为:

#import <Foundation/Foundation.h> 
#import <UIKit/UIKit.h> 

@class MyAppDelegate 

@interface UIViewController (MyCategory) 

-(MyAppDelegate *) appDelegate; 

@end 

然后把进口的.m文件,而不是。这实际上是一个很好的总体原则。在可能的情况下,在头文件中使用前向类声明,并将导入放入实现文件中。

+0

谢谢你的回答。 – Centurion

1
-(id)appDelegate{ 
    return [[UIApplication sharedApplication] delegate]; 
} 

//Calling code 
MyAppDelegate* delegate = (MyAppDelegate*)[self appDelegate]; 
+0

用于清洁设计。如果你指出为什么在高级框架类中包含这样的本地化方法签名是一个坏主意,那将会更好。 – Perception

+0

我把它放到一个类别的东西,因为我想有一个方便的快捷方式,而不是长长的代码行。我试图拥有的快捷方式会表现得像一个属性,但它只是一种方法。在我的情况下,我想访问我的主要应用程序委托像self.appDelegate.someProperty。 – Centurion

+0

@Perception:它是如何干净的设计必须投入类型? – JeremyP

0

添加@class MyAppDelegate;到你的类别头部的顶部,让编译器知道这个类别存在或其头部为#import

通常,在MyAppDelegate中使用类方法可能会更好。从概念上讲,appDelegate不是您的方法暗示的单个视图控制器的属性。

+0

我正在尝试改进我的架构。我的应用程序有6个UIViewController屏幕,每个MVC在屏幕上执行弹出/推送其他MVC。我需要指向每个UIViewController的所有MVC。但我不喜欢指针解决方案。我也不喜欢使用通知的想法。然后我得到一个建议,让主要应用程序委托类中的所有必要指针都显示在我的屏幕上,并使用sharedApplication访问它们。但访问代码很长,所以我想有一个快捷方式,比如self.appDelegate.someMyUIViewController。但无法使其与类别合作。 – Centurion

相关问题