0

I'm creating an Objective-C category on the UIViewController class. In my project, I want one singular and easy way to get the app delegate.

Here's what I'm doing

// header file UIViewController+AppDelgate.h
#import <UIKit/UIKit.h>

@class ExampleAppDelegate;

@interface UIViewController (AppDelegate)
@property (weak, nonatomic, readonly) ExampleAppDelegate *appDelegate;
@end

// implementation file UIViewController+AppDelegate.m
#import "UIViewController+AppDelegate.h"
#import "ExampleAppDelegate.h"

@implementation UIViewController (AppDelegate)

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

@end

Should I define the property as weak? I think it would be bad to retain this guy as it would normally have retains on view controllers referenced within.

4

3 回答 3

1

weak/strong in this case is a moot point, since there is no local instance variable holding a pointer. ARC will do the right thing (i.e. it will not send more retains than releases for any given scope).

于 2012-06-16T00:50:59.873 回答
0

Why not create a Utility class with a class method that does the same thing, then you can reference it something like:

[Utility appDelegate];

and you wont have to add a property to every single ViewController that needs to access the AppDelegate, the way you currently have it setup.

于 2012-06-16T00:47:38.953 回答
0

From the looks of your implementation you dont need to define a property, you only need to declare the method -(ExampleAppDelegate *)appDelegate;

This of course would only work if called on an instance of the class unless you made it a class method.

于 2012-06-16T00:48:26.877 回答