Reputation: 113
My app has 3 components:
When the button is pressed, the whole app freezes(but does not crash)and I have no idea why. I tried searching about this online, but none have solved my problem.Is there anything I can check for errors, or what reasons can a button freeze an app.
Here is my code:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var text: UITextField!
@IBOutlet weak var label: UILabel!
var i = 2
@IBAction func buttonPressed(_ sender: Any) {
if let userEnteredText = text.text{
var isPrime = true
let number:Int = Int(userEnteredText)!
while i < number{
if number % i == 0{
isPrime = false
i = i + 1
}
if isPrime == true{
label.text = "\(number) is Prime"
label.textColor = UIColor.black
}else{
label.text = "\(number) is not Prime"
label.textColor = UIColor.black
}
}
}else{
label.text = "Error-Enter a positive integer"
label.textColor = UIColor.red
}
}
}
Upvotes: 0
Views: 429
Reputation: 8550
Because the i++ should be outside of the if statement
...
while i < number{
i = i + 1
if number % i == 0 {
isPrime = false
}
...
Please note : Since you are trying to compute something that can take sometimes, you'll have(when you learn a little more) to do this kind of computation outside of the main thread. Your apps locks because you are blocking the main thread which is the one controlling the UI/touch/interaction of your app. Look into dispatch_async
PPS : Learn how to point break point in XCode and step over/into, you'll be able to debug the flow of your app.
Upvotes: 1