如果一个对象在 appDelegate 中实例化,它是否永远存在?



我正在学习一个教程,该教程使用作者所述的称为反向依赖注入的术语。 基本上,它是一个待办事项列表应用程序,可以实例化跟踪所有待办事项,重新排列等的ItemStore对象。 在本教程中,我们实例化了 AppDelegate 中的 ItemStore 对象,该对象可通过 UITableViewController 的解包属性在 UITableViewController 中访问。 我的问题是,如果 ItemStore 对象在应用程序委托中实例化,它是否在应用程序的整个生命周期中存在? 而且,如果是这样,因为它不是单例,这是否意味着每次我在应用程序中显示 UITableViewController 时,它都会创建内存泄漏或保留周期?

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
//create an ItemStore
let itemStore = ItemStore()
//now access the ItemsViewController and set its item store
let itemsController = window!.rootViewController as! ItemsTableViewController
itemsController.itemStore = itemStore
//we just set the itemStore property of the ItemsTableViewController!  Yayy, WHEW!! Now when the ItemsTableViewController is accessed with that unwrapped ItemStore object then it will be set!!! WHHHHEEEEWWWWW!
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

}

@Joakim已经给出了一个很好的答案。 我们可以从任何类访问variable,如果它被声明为类attributeAppDelegate类具有singleton对象。 我们可以通过这种方式访问它。

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let aVariable = appDelegate.someVariable

因此,它始终返回具有相同数据的相同对象,您可以从所需的任何类访问它,但方法中的变量只能通过此方法访问。

最新更新