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 playerviewcontroller
in both Appdelegate.h
and Appdelegate.m
files.
在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 volumeDelegate
value 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 AppDelegate
object 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 appdelegate
member 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 init
doesn't make viewController's view to load! viewDidLoad
is not called at all.
但alloc init
不会使 viewController 的视图加载!viewDidLoad
根本没有被调用。