如何在多个视图控制器中制作一个iAd标语的共享实例? [英] How to make a single shared instance of iAd banner throughout many view controllers?
问题描述
我尝试在我的应用程序委托中使用单例类,但无法使其正常工作.我还检查了iAdSuite示例(尤其是containerBanner示例,因为它似乎是最亲密的),但我无法弄清楚.如果有一种更好的方法可以在不使用单例类的情况下完成此任务,并且您可以为我指明正确的方向,我将非常感激.我的一些单例课程代码如下.谢谢!
I have tried using a singleton class in my app delegate but I haven't been able to get that to work. I've also checked out the iAdSuite examples (particularly the containerBanner example because it seemed to be the most relative) but I can't figure it out. If there's a better way to accomplish this without using a singleton class and you can point me in the right direction I'd really appreciate it. Some of my singleton class code is below. Thank you!
@interface App Delegate
@property (assign) iAdController *iadc;
+ (AppDelegate*) sharedApplication;
- (iAdController*)sharedAd;
@end
@implementation AppDelegate
@synthesize iadc;
+ (AppDelegate*) sharedApplication
{
return [[UIApplication sharedApplication] delegate];
}
-(iAdController*)sharedAd
{
if(iadc==nil){
iadc=[iAdController new];
}
return iadc;
}
@interface ViewController
iAdController*iadc=[[AppDelegate sharedApplication] sharedAd];
//here i get an error saying, "initializer element is not a compile-time constant.
一切都正确导入.如果还有其他事我应该发贴告诉我.
Everything is imported correctly. If there's anything else I should post let me know.
推荐答案
尝试将您的单例创建更改为此:
try changing your singleton creation to this:
+ (LocationManagerSingleton*)sharedInstance {
static LocationManagerSingleton *_sharedInstance;
if(!_sharedInstance) {
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedInstance = [[super allocWithZone:nil] init];
});
}
return _sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone {
return [self sharedInstance];
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
- (id)init
{
self = [super init];
if (self != nil)
{
// PERFORM any custom initialization here
}
return self;
}
显然要更改类的名称.
只要您想在任何一个视图控制器中使用单例,就可以这样称呼它:
Whenever you want to use your singleton in any of your viewcontrollers just call it like this:
locationManager = [LocationManagerSingleton sharedInstance];
不要忘记添加
+ (LocationManagerSingleton*) sharedInstance;
标题上.
编辑
好吧,我似乎误解了您的代码(忘了我的答案,您只是想能够从任何地方访问iAdController.因此只需放置
well it seems i misunderstood your code (forget my answer, you simply want to be able to access your iAdController from everywhere. so just place
在ViewController的.m中添加
Add inside the .m of the ViewController
@interface ViewController()
{
iAdController *iadc;
}
在
-(void)viewDidLoad
{
iadc=[[AppDelegate sharedApplication] sharedAd];
}
但是将应用委托.h导入到您要在其中使用的任何视图控制器上.
but import the app delegate.h on whichever viewcontroller you want to use it in.
#import "AppDelegate.h"
在@interface的AppDelegate中也不应有空格
also there shouldnt be a space in the AppDelegate on the @interface
这篇关于如何在多个视图控制器中制作一个iAd标语的共享实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!