How to make a single shared instance of iAd banner throughout many view controllers?

最后都变了- 提交于 2019-12-08 07:00:55

问题


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.


回答1:


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;
}

Obviously change the name of the class.

Whenever you want to use your singleton in any of your viewcontrollers just call it like this:

locationManager = [LocationManagerSingleton sharedInstance];

Dont forget to add

+ (LocationManagerSingleton*) sharedInstance;

on the header.

EDIT

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

Add inside the .m of the ViewController

@interface ViewController()
{
    iAdController *iadc; 
}

And inside the

-(void)viewDidLoad
{
    iadc=[[AppDelegate sharedApplication] sharedAd];
}

but import the app delegate.h on whichever viewcontroller you want to use it in.

#import "AppDelegate.h" 

also there shouldnt be a space in the AppDelegate on the @interface



来源:https://stackoverflow.com/questions/11895661/how-to-make-a-single-shared-instance-of-iad-banner-throughout-many-view-controll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!