I need to attach a method to all my UIViewControllers. The method just returns a pointer to my main app delegate class object. However, xcode 4 throws an error “parse issue expected a type” in header file at the declaration of output parameter type MyAppDelegate. If I change it to the other type, for example id, then the error goes away. But I’m using a dot syntax to access main app delegate properties and if I will change the type to id then xcode4 not recognize my main app delegate properties. I have included the definition file of category to those UIViewController class files where I’m accessing this method. Here is definition of my category:
#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
Here is an implementation:
#import "MyCategory.h"
@implementation UIViewController (MyCategory)
-(MyAppDelegate *)appDelegate{
MyAppDelegate *delegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
return delegate;
}
EDIT: The reason why I’m implementing this category is that I need to have handy shortcut for accessing my main app delegate from any place of the code (in my case from UIViewControler objects):
// handy shortcut :)
self.appDelegate.someMethod;
//not so handy shortcut :(
MyAppDelegate *delegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
I think you have a dependency cycle in your header files. If
MyAppDelegate.himportsMyCategory.heither directly or indirectly, the first time the category declaration is compiled the compiler won’t know what aMyAppDelegateis. You should remove the import ofMyAppDelegate.hfrom theMyCategory.hheader and replace it with a forward class declaration:Then put the import in the
.mfile instead. This is actually a good general principle. Where possible, use forward class declarations in the headers and put imports in the implementation file.