2

What exacly the AppDelegates method is given in Xcode?? I have so many classes in my app. Now i want is that i have AudioStreamer class and i have to use that class in most other classes... And I want to have only one instance of AudioStreamer class. So that it will be easy to handle one object. Is it feasible to declare AudioStreamer class in AppDelegate file and make instance in that file only... Can I access that variable in all the other class.???

DShah
  • 9,768
  • 11
  • 71
  • 127
  • Make the `AudioStreamer` class a [singleton](http://stackoverflow.com/questions/145154/what-does-your-objective-c-singleton-look-like) – albertamg Jul 26 '11 at 12:58

3 Answers3

3

I would recommend a singleton so that only one instance is created and shared by all clients.

I suggest Matt Galaghers posting about singletons and his downloadable SynthesizeSingleton.h:

http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html

Kay
  • 12,918
  • 4
  • 55
  • 77
  • So exactly where should i implement this singleton??? will it be good to declare in AppDelegate – DShah Jul 26 '11 at 13:15
  • 1
    No just in AudioStreamer. Declare a class method "+(AudioStreamer) sharedAudioStreamer", include SyntesizeSingleton.h in .m file and than you can access your singleton instance with [AudioStreamer sharedAudioStreamer]. I changed the original file a bit so that my access method is always called sharedInstance and not sharedWhatEver, but do it as you like it. – Kay Jul 26 '11 at 13:24
2

You could use very handy GCD (Grand Central Dispatch) functions to achieve Singleton behavior on these lines -

+ (AudioStreamer*) defaultStreamer {
    static AudioStreamer* defaultStreamer = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        defaultStreamer = [[AudioStreamer alloc] init];
    });
    return defaultStreamer; 
} 
the.evangelist
  • 488
  • 5
  • 18
  • +1 Although I will stay with classical singleton, this is an interesting and creative approach - I'll keep it in the back of my head :-) – Kay Jul 26 '11 at 13:17
  • So when i will call this method from different classes.. will it give me only one same instance everytime?? I want to refer to only one instance everytime.. – DShah Jul 26 '11 at 13:18
  • @Dhiren - Yes, thats correct! you would always have a 'single' instance of your AudioStreamer throughout the app. – the.evangelist Jul 26 '11 at 13:22
1

You can also access the objects declared as properties in appDelegate thru out ur app like this.

myFirstAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
myStr=[appDelegate.mainArray objectAtIndex:1];

In the above example I have shown how to access the array which I have declared and retained in appDelegate class. In this way you can access any objects you want which are declared as properties,thru out ur app. Hope this helps.

stack2012
  • 2,146
  • 2
  • 16
  • 23