tj75467
tj75467

Reputation: 113

When I press a button in my app ,the whole app freezes

My app has 3 components:

  1. A textfield where the user enters a number to see if the number is prime or not
  2. A button that when pressed does an action to determine if the number is prime or not
  3. A label that shows whether the number is prime or not

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

Answers (1)

Yahel
Yahel

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

Related Questions