简体   繁体   English

每次加载viewDidLoad

[英]viewDidLoad loads every time

I'm doing a simple project, using firebase. 我正在使用Firebase做一个简单的项目。

In my viewDidLoad fiction I'm creating an object of the class. 在我的viewDidLoad小说中,我正在创建该类的对象。 I want to to be created only once during my work cycle. 我只想在工作周期中被创建一次。 But, it creating a new objects every time i'm visiting this ViewController. 但是,每次我访问此ViewController时,它都会创建一个新对象。

override func viewDidLoad() {
    super.viewDidLoad()

    let urlArray = ["http://i.imgur.com/VAWlQ0S.gif", "http://i.imgur.com/JDzGqvE.gif", "http://67.media.tumblr.com/4cd2a04b60bb867bb4746d682aa60020/tumblr_mjs2dvWX6x1rvn6njo1_400.gif", "https://media.giphy.com/media/TlK63ELk5OPDzpb6Tao/giphy.gif", "http://i3.photobucket.com/albums/y90/spicestas/GeriHalliwell-Calling-new1.gif", "http://media.tumblr.com/tumblr_lnb9aozmM71qbxrlp.gif"]

    var counter = 1

    for url in urlArray {

       let nsUrl = NSURL(string: url)

       let girls = ProfileClass()

       girls.profilePhotoUrl = url
       girls.profileGender = "female"
       girls.profileName = "girlsname\(counter)"
       girls.profileSurname = "girlsurname\(counter)"
       girls.interest = "men"
       girls.uid = "\(randomStringWithLength(45))"

       counter++
       girls.SaveUser()


}

Maybe I should write my code in another function? 也许我应该在另一个函数中编写代码? Or the problem maybe be caused by my for loop? 还是问题可能是由我的for循环引起的?

You should create another class that handles your data. 您应该创建另一个处理数据的类。 Call it your data manager. 称它为数据管理器。

Make this a singleton, or make it a member of your app delegate, or whatever. 使其成为单例,或使其成为应用程序委托的成员,或其他。

When you load the view controller in question, get the data from this object. 当您加载有问题的视图控制器时,请从该对象获取数据。

This is a nice little article on singletons in Swift 这是一篇关于Swift中单例的不错的小文章

https://thatthinginswift.com/singletons/ https://thatthinginswift.com/singletons/

If you want your code to be executed only when the app is launched then move it inside the 如果您希望仅在启动应用程序时执行代码,则将其移至

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

of your AppDelegate. 您的AppDelegate。

This way it will be executed only when the user does launch your app. 这样,只有当用户启动您的应用程序时,它才会执行。

As rigdonmr said in the comments below, there are several techniques you can use when you want run a block of code only once. 就像rigdonmr在下面的评论中说的,当您只想运行一次代码块时,可以使用多种技术。 My answer instead specifically tells you how to run a block of code once during when the app is launched . 我的答案是专门告诉您如何在启动应用程序期间运行一次代码块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM