如何创建AppDelegate
的sharedInstance
并在我的应用程序中任何地方使用。
如何创建AppDelegate
的sharedInstance
并在我的应用程序中任何地方使用。
使用方法:
在AppDelegate.h中:
+ (AppDelegate *)sharedAppDelegate;
在AppDelegate.m中
+ (AppDelegate *)sharedAppDelegate{
return (AppDelegate *)[UIApplication sharedApplication].delegate;
}
在Constants.h中声明语句。
#define myappDelegate ((AppDelegate *)[[UIApplication sharedApplication] delegate])
如果在.pch文件中声明了Constants.h,那么您可以在应用程序中的任何地方使用myappDelegate
。请参考此文了解Xcode 6中的PCH。
#import "AppDelegate.h"
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
-(AppDelegate*) app
{
return (AppDelegate*) [[UIApplication sharedApplication] delegate];
}
#define myAppDelegate (AppDelegate *)[[UIApplication sharedApplication] delegate]
并且像这样使用 myAppDelegate.someVariable 或 [myAppDelegate somemethod]
在Swift中
Swift >= 1.2(引入Xcode 6.3)
let myAppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let aVariable = myAppDelegate.someVariable
Swift < 1.2
let myAppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let aVariable = myAppDelegate.someVariable
// AppDelegate.swift
static var shared = AppDelegate() // Declare a static variable as an instance of AppDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Singleton
AppDelegate.shared = self // set the value of "shared" to the current instance
return true
}
使用方法
AppDelegate.shared
使用这个:
+ (AppDelegate *)appDelegate
{
return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}
任何ViewController都可以在包括Xcode 8在内的此appDelegate中工作
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];