如何在iOS中创建AppDelegate共享实例?

4

如何创建AppDelegatesharedInstance并在我的应用程序中任何地方使用。


请使用以下宏定义:#define myappDelegate ((AppDelegate *)[[UIApplication sharedApplication] delegate]) - Smile
你需要用Objective-C还是Swift? - Govindarao Kondala
AppDelegate *appdelegate =((AppDelegate *)[[UIApplication sharedApplication] delegate])AppDelegate *appdelegate = ((AppDelegate *)[[UIApplication sharedApplication] delegate]) - Smile
AppDelegate已经在整个应用程序中共享,您可以像[[UIApplication sharedApplication] delegate]一样使用它的实例。 - channi
2
你有搜索过吗? - Ankit Srivastava
7个回答

10

使用方法:

在AppDelegate.h中:

+ (AppDelegate *)sharedAppDelegate;

在AppDelegate.m中

+ (AppDelegate *)sharedAppDelegate{
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}

1
如何处理出现在返回行上的信息? [UIApplication delegate] 只能从主线程中使用。 - Yuliwee

3

在Constants.h中声明语句。

#define myappDelegate ((AppDelegate *)[[UIApplication sharedApplication] delegate])

如果在.pch文件中声明了Constants.h,那么您可以在应用程序中的任何地方使用myappDelegate。请参考此文了解Xcode 6中的PCH。


1
在每个视图控制器中使用此代码。
#import "AppDelegate.h"

  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

或者您可以在ViewController子类中创建一个方法,并在每个ViewController中使用它。
-(AppDelegate*) app
{
   return (AppDelegate*) [[UIApplication sharedApplication] delegate];
}

在UIViewController的子类中 - 将其作为所有视图控制器的基类。然后,[self app]可以正常工作,您不必保留引用。

1
您可以像下面这样使用:
在Objective C中:您可以将以下行添加到.pch文件中,并在需要时使用。
#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

0
其他答案使用UIApplication.shared.delegate,但你需要始终编写'as! AppDelegate',因此Swift更清晰的代码:
// 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

0

使用这个:

+ (AppDelegate *)appDelegate
{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

-3

任何ViewController都可以在包括Xcode 8在内的此appDelegate中工作

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接