hoju
hoju

Reputation: 33

Objective-C cocoa touch: declaring properties over and over different view controllers

This might be a stupid question, but I've found myself getting tired of declaring same property over and over multiple view controllers. Is there a better design to do something simple as below:

Consider this: I have a SoundManager class that is used throughout my iphone project. This class simply plays audio (click sound) when a user presses button.

Now, I have been doing this:

ViewController A: .h

SoundManager *mgr;
@property (nonatomic,retain) SoundManager *mgr;

ViewController A: .m

@synthesize *mgr;

and in viewDidLoad

if (mgr == nil)
  mgr = [[SoundManager alloc] init];

Then I repeat this over all my view controllers. This is cumbersome to say the least. There must be a better way of doing something like this - or at least a code generator utility that I could use?

Anyone have any suggestions?

Upvotes: 1

Views: 102

Answers (2)

You could implement a singleton for that class:

@interface SoundManager : NSObject
{
    //your ivars
}

//your @properties

//singleton
 + (id)sharedManager;

@end

@implementation SoundManager

//synthesize

static SoundManager *instance = nil;
+ (id)sharedManager
{
    //you may want to add a @synchronized() here
    if (instance == nil)
    {
        instance = [[SoundManager alloc] init];
    }
    return instance;
}
@end

Then call [SoundManager sharedManager] wherever you need a SoundManager instance.

Upvotes: 1

Wolfgang Schreurs
Wolfgang Schreurs

Reputation: 11834

Sounds like the whole app uses the same instance of SoundManager? Perhaps a Singleton pattern would be more usable. Or otherwise create a custom view controller with the mentioned functionality and make all other view controllers inherit from this custom view controller.

Upvotes: 0

Related Questions