Getting appdelegate value from viewcontroller

AlgoCoder picture AlgoCoder · Aug 23, 2013 · Viewed 25.3k times · Source

In Appdelegate.h
I imported the playerviewcontroller in both Appdelegate.h and Appdelegate.m files.

  @class PlayerViewController; 
  @property(nonatomic)float volumeDelegate;        

In Appdelegate.m

  @synthesize volumeDelegate;
 - (void)volumeChanged:(NSNotification *)notification
 {
volumeDelegate =1.0
    PlayerViewController *volumeObject=[[PlayerViewController alloc]init];
[volumeObject setVolumeForAVAudioPlayer];
}

In Playerviewcontroller.h

 -(void)setVolumeForAVAudioPlayer;

In Playerviewcontroller.m

@interface PlayerViewController ()
{
AppDelegate *appdelegate;

 }
  -(void)viewDidLoad
  {
  appdelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  }

  -(void)setVolumeForAVAudioPlayer
  {
[appdelegate.sharedplayer  setVolume:appdelegate.volumeDelegate];
NSLog(@"System Volume in player view:  %f",appdelegate.volumeDelegate);
 }

When i run this I get volumeDelegate value as Zero as below.

System Volume in player view:0.000000000

What is the Mistake I'm making here

Answer

Hemang picture Hemang · Aug 23, 2013

You can access to the AppDelegate object like below

Objective-C

Define it like this:

AppDelegate appDelegate;

Access it like this:

appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

Usage:

- (void)setVolumeForAVAudioPlayer
{
    [appDelegate.sharedplayer  setVolume:appdelegate.volumeDelegate];
    NSLog(@"System Volume in player view:  %f",appDelegate.volumeDelegate);
}

Swift:

Define it like this:

let appDelegate = UIApplication.shared.delegate as! AppDelegate

Usage:

func setVolumeForAVAudioPlayer() 
{
    appDelegate.sharedPlayer.setVolume:appDelegate.VolumeDelegate
    print("System Volume in player view: \(appDelegate.volumeDelegate)")
}