问题
I am new to iPhone development. My objective is to implement a singleton class for iAd, so that I share the single instance of iAd over multiple view controllers?
Any help on the implementation side will be much appreciated?
回答1:
In your AppDelegate.h
@property (assign) YouiAdClass*iADObject
+ (AppDelegate*) sharedApplication;
+ (YouriAdClass*)sharedAd
In your AppDelegate.m
@synthesize iADObject
+ (AppDelegate*) sharedApplication
{
return [[UIApplication sharedApplication] delegate];
}
+(YouriAdClass*)sharedAd
{
if(iAdObject==nil){
iADObject=[YouriAdClass new]
}
return iADObject;
}
Now when you want to get your object in any place just call
YouriADClass*iadObject=[[AppDelegate sharedApplication] sharedAd];
And you will get always the same pointer. Remember to import AppDelegate andYouriADClass in your header files.
来源:https://stackoverflow.com/questions/11017759/implementing-iad-using-singleton-class