ios 从视图控制器获取 appdelegate 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18401799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting appdelegate value from viewcontroller
提问by AlgoCoder
In Appdelegate.h
I imported the playerviewcontrollerin both Appdelegate.hand Appdelegate.mfiles.
在Appdelegate.h
我进口playerviewcontroller均Appdelegate.h和Appdelegate.m文件。
@class PlayerViewController;
@property(nonatomic)float volumeDelegate;
In Appdelegate.m
在 Appdelegate.m
@synthesize volumeDelegate;
- (void)volumeChanged:(NSNotification *)notification
{
volumeDelegate =1.0
PlayerViewController *volumeObject=[[PlayerViewController alloc]init];
[volumeObject setVolumeForAVAudioPlayer];
}
In Playerviewcontroller.h
在 Playerviewcontroller.h 中
-(void)setVolumeForAVAudioPlayer;
In Playerviewcontroller.m
在 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 volumeDelegatevalue as Zero as below.
当我运行它时,我得到的volumeDelegate值为零,如下所示。
System Volume in player view:0.000000000
播放器视图中的系统音量:0.000000000
What is the Mistake I'm making here
我在这里犯了什么错误
回答by Hemang
You can access to the AppDelegateobject like below
您可以访问AppDelegate如下对象
Objective-C
目标-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)")
}
回答by iHunter
You're initializing the appdelegatemember variable in a viewDidLoad, but that method is not called at the moment you call setVolumeForAVAudioPlayer!
您正在 a 中初始化appdelegate成员变量viewDidLoad,但在您调用setVolumeForAVAudioPlayer!
You're doing
你正在做的
PlayerViewController *volumeObject=[[PlayerViewController alloc]init];
[volumeObject setVolumeForAVAudioPlayer];
But alloc initdoesn't make viewController's view to load! viewDidLoadis not called at all.
但alloc init不会使 viewController 的视图加载!viewDidLoad根本没有被调用。

