Reputation: 2268
I'm doing a simple project, using firebase.
In my viewDidLoad fiction I'm creating an object of the class. 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.
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?
Upvotes: 0
Views: 138
Reputation: 59496
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.
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. My answer instead specifically tells you how to run a block of code once during when the app is launched.
Upvotes: 0
Reputation: 652
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
https://thatthinginswift.com/singletons/
Upvotes: 3