Cannot find the error in this sequence. Thread 1: signal SIGABRT - ios

I have just started to code, but I have already encountered some error which I cannot figure out. Would you please help me?
class ViewController: UIViewController {
#IBOutlet var getNumber: UITextField!
#IBAction func computePrime(_ sender: AnyObject) {
if let userString = getNumber.text { // Convert input to Int
let userNumber = Int(userString)
if let number = userNumber {
var i = 2 // Variable declaration
var prime = true
while i < number { // Prime calculation
if number & i == 0 {
prime = false
i = number
} else {
i += 1
}
}
if prime == false { // Output result
displayResult.text = "It is not prime"
} else {
displayResult.text = "It is prime"
}
} else {
displayResult.text = "Please enter a positive whole number" // Error message in case value entered is not good
}
}
}
#IBOutlet var displayResult: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
When I try to run it, the app crashes and it gives me this error:
"Thread 1: signal SIGABRT"
highlighting this line:
"class AppDelegate: UIResponder, UIApplicationDelegate {"
from the AppDelegate.swift file, which I have not modified.
How can I fix it?
Thank you!

Probably you don't have connected in Storyboard the getNumber and displayResult (IBOutlet) object.
Check that answer:
IBOutlet not connecting in SWIFT

The highlighted line is at the application delegate because the system regressed all the way back to the top trying to find a layer with an exception handler for the exception that was thrown. Check the last few lines of the Xcode console for a description of the exception which may tell you where it was caused.
You can add an "Exception Breakpoint" to stop execution at the moment of the exception to see the point of origin. Many articles exist on how to do this.

Related

SIGABRT error in swift 2

I recently updated my app to Swift 2, and had one error, which I solved thanks to you guys.
And now, I have a second error, which is at runtime, when I press the one button to play a sound. It is a signal SIGABRT error.
Here is the error message I get in the debug console:
2016-01-25 09:16:09.019 WarningShot1.0.0[291:19030] -[WarningShot1_0_0.ViewController playMySound:]: unrecognized selector sent to instance 0x135547d30
2016-01-25 09:16:09.021 WarningShot1.0.0[291:19030] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[WarningShot1_0_0.ViewController playMySound:]: unrecognized selector sent to instance 0x135547d30'
*** First throw call stack:
(0x182835900 0x181ea3f80 0x18283c61c 0x1828395b8 0x18273d68c 0x18755fe50 0x18755fdcc 0x187547a88 0x18755f6e4 0x18755f314 0x187557e30 0x1875284cc 0x187526794 0x1827ecefc 0x1827ec990 0x1827ea690 0x182719680 0x183c28088 0x187590d90 0x10005e2e0 0x1822ba8b8)
libc++abi.dylib: terminating with uncaught exception of type NSException
Also, this is the part of the code where it throws this error, in the second line, where the class is declared:
import UIKit
#UIApplicationMain
-> class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
What is happening here? What am I missing / misnaming? What do I need to change in my code to get ot running again. This app is ridiculously simple, and worked for months under the last version of Swift. Why is it now giving me errors?
Thank you for your help.
Here is the code for my ViewController.swift file:
import UIKit
import AVFoundation
import CoreMotion
class ViewController: UIViewController {
var myPlayer = AVAudioPlayer()
var mySound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("RemSound_01", ofType: "wav")!)
func initYourSound() {
do {
try myPlayer = AVAudioPlayer(contentsOfURL: mySound, fileTypeHint: nil)
myPlayer.prepareToPlay()
// myPlayer.volume = 1.0 // < for setting initial volume, still not perfected.
} catch {
// handle error
}
var motionManager = CMMotionManager()
var currentMaxAccelY : Double = 0.0
func viewDidLoad() {
super.viewDidLoad()
initYourSound()
// Do any additional setup after loading the view, typically from a nib.
//set motion manager properties
motionManager.accelerometerUpdateInterval = 0.17
//start recording data
// motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler: {
// (accelerometerData: CMAccelerometerData!,error:NSError!) -> Void in
// self.outputAccelerationData(accelerometerData.acceleration)
// if(error != nil) {
// print("\(error)")
// }
// })
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler: {
(accelerometerData,error) in outputAccelerationData(accelerometerData!.acceleration)
if(error != nil) {
print("\(error)", terminator: "")
}
})
}
//func outputAccelerationData(acceleration : CMAcceleration){
// accY?.text = "\(acceleration.y).2fg"
//if fabs(acceleration.y) > fabs(currentMaxAccelY)
//{
// currentMaxAccelY = acceleration.y
//}
// maxAccY?.text = "\(currentMaxAccelY) .2f"
//}
func outputAccelerationData(acceleration : CMAcceleration){
if fabs(acceleration.y) >= 1.25 {
myPlayer.play()
}
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func playMySound(sender: AnyObject) {
myPlayer.play()
}
// self.resetMaxValues()
// #IBOutlet var accY: UILabel!
// #IBOutlet var maxAccY: UILabel!
// #IBAction func resetMaxValues() {
// currentMaxAccelY = 0
// }
}
}
"unrecognized selector sent to instance" means that there is a mismatch between the action-name in "addTarget()" and the name of the function you want to call. Probably something with the parameters of the function.. It's hard to say without seeing any code.
action: Selector("playMySound:")
would expect to find a function:
func playMySound(sender: AnyObject?) {};
To easier track what's happening, you might add a symbolic breakpoint for all exceptions. You do that in Xcode on the "exceptions" tab (left part of the window) and when an exception is thrown, Xcode stops like usual and you might look up the stack trace. If the call is synchronous, you should easily find and see your mistake.
EDIT: Oh well, you seem to have done the user interface using a XIB file. The mistake could be, you wired the button's action in the XIB file to the view controller. If you later change the method's signature (parameter, name, etc.), UIKit can't find the method. Open the XIB and fix your error. ;-)

I am getting errors such as " braced block of statements is an unused closure" and expected expression

This is my first time doing a simple project in swift and these errors are bugging me for last couple of hours. I have this code below and even though i have curly braces around and statements inside the if/else i still get that errors. Any help would be greatly appreciated guys.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var `switch`: UISwitch!
#IBOutlet var Answer: UILabel!
#IBOutlet var tempInput: UITextField!
//aqnswer value
#IBAction func switchPressed(sender: AnyObject)
{
if switch.on {
self.Answer.text = "cel to fah"
}
else {
self.Answer.text = "fah to cel"
}
}
//textfield value
#IBAction func calculate(sender: AnyObject)
{
//get user input
// value = celcius
var Value:Int = tempInput.text.toInt()!
var toFah :Int = ( 32 + Value * 9 ) / 5
//to celcius
var toCel: Int = (Value-32) * 5 / 9
if switch.on {
self.Answer.text = toFah.description
}
else {
self.Answer.text = toCel.description
}
// println(fah)
// Answer.text = fah.description
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The Swift Language Guide says:
If you need to give a constant or variable the same name as a reserved
Swift keyword, surround the keyword with back ticks (`) when using it
as a name. However, avoid using keywords as names unless you have
absolutely no choice.
In your example you have indeed a choice…
But if you really really really want to use switch as a variable name you have to wrap all occurrences of switch in back ticks.

Swift error about consecutive declarations on a line

I don't understand what's wrong with this code in my View Controller, the very bottom line (with the single } bracket) keeps getting two errors, one that states "Consecutive declarations on a line must be separated by ';'" and "expected declaration". When I add the semicolon where it directs me to it still says an expected declaration error....but for what? Can anyone find anything wrong with it?
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var testObject = PFObject(className:"TestObject")
testObject["foo"] = "bar"
testObject.saveInBackgroundWithTarget(nil, selector: nil)
var voteCount = PFObject(className:"VoteCount")
voteCount["votes"] = 0
voteCount["optionName"] = "Crepes"
voteCount.incrementKey("votes")
voteCount.saveEventually()
var query = PFQuery(className:"VoteCount")
query.getObjectInBackgroundWithId("e8KhneiSfw") {
(voteCount: PFObject!, error: NSError!) -> Void in
if error != nil {
NSLog("%#", error)
} else {
voteCount["votes"] = 1
voteCount.incrementKey("votes")
voteCount.saveEventually()
}
}
class Counter {
var voteCount: Int = 0
func incrementBy(amount: Int, numberOfTimes times: Int) { voteCount += amount * times
}
}
func didReceiveMemoryWarning() {
didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
There's a missing closing brace before this line:
class Counter {
Your viewDidLoad() method is not properly closed, so what happens is that the class and didReceiveMemoryWarning are defined as local to viewDidLoad.
A proper indentation usually reveals errors like that... are you properly indenting your code?
As written, class Counter and func didReceiveMemoryWarning() are inside viewDidLoad. Fix your braces.

'UInt32' is not convertible to 'MirrorDisposition'

EDIT:
Ok. I just changed my code as: var randomX = Int(arc4random()%6) Wish i could think of it before posting here :|
I took accepted answer of this topic as reference: Swift convert UInt to Int
I've been trying to make a simple ios guessing app with swift. I'm generating a random number and getting another number from user and comparing both. But i'm stuck with this error: 'UInt32' is not convertible to 'MirrorDisposition' while comparing two integers (one of them converted from string to integer by toInt() method)
Below you can see my ui, my code, two stackoverflow topics i read and how i changed my code after reading those topics.
UI: (i couldn't resize the image)
my code:
import UIKit
class ViewController: UIViewController {
#IBOutlet var myImageView: UIImageView!
#IBOutlet var inputField: UITextField!
#IBAction func clickedGuessButtonAction(sender: AnyObject) {
println("Guess button clicked")
var randomX = arc4random()%6
println("randomX = \(randomX)")
var guess = inputField.text.toInt()
if((inputField.text) != nil){
if(guess == randomX){
println("correct")
var image = UIImage(named: "images/tick.png");
myImageView.image=image;
self.view.addSubview(myImageView); // what is this?
inputField.resignFirstResponder();// hides keyboard
}
else
{
println("wrong")
var image = UIImage(named: "images/cross.png")
myImageView.image=image;
self.view.addSubview(myImageView);
inputField.resignFirstResponder();//hides keyboard
}
}
else{
println("invalid input. requires integer only")
inputField.resignFirstResponder();// hides keyboard
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I found these topics on stackoverflow:
float is not convertible to 'MirrorDisposition' Swift What is mirrordisposition?
iOS Swift Error: 'T' is not convertible to 'MirrorDisposition'
First one especially has an extended answer finally suggesting if intValue == Int(floatValue)
Than i changed var guess = inputField.text.toInt()
to var guess = Int(inputField.text);
But this time i'm getting an error message like this: Cannot invoke 'init' with an argument of type '#lvalue String!'
This time, i searched this error message but couldn't find anything helpful. It shouldn't be this difficult to compare 2 integers. I'm definitely missing something easy. Any ideas?
Try changing:
var randomX = arc4random()%6
to
var randomX = Int(arc4random()%6)
this should do it
let sizeX = UInt32(6)
let randomX = CGFloat(arc4random_uniform(sizeX))

fatal error: unexpectedly found nil while unwrapping an Optional value [duplicate]

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 2 years ago.
I am trying to run this code but I keep on getting this error:
fatal error: unexpectedly found nil while unwrapping an Optional value
I don't understand what it means or why I'm getting it. Any hint?
import UIKit
class ViewController: UIViewController {
var lastNumber: String = ""
#IBOutlet var answerField: UILabel
#IBOutlet var operaterLabel: UILabel
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func buttonTapped(theButton: UIButton) {
if answerField.text == "0"
{
answerField.text = theButton.titleLabel.text
}
else
{
answerField.text = answerField.text + theButton.titleLabel.text
}
}
#IBAction func plusTapped(theButton: UIButton) {
// error is talking about the next line
if operaterLabel.text == ""
{
operaterLabel.text = "+"
lastNumber = answerField.text
answerField.text = "0"
}
else
{
enterTapped(nil)
operaterLabel.text = "+"
}
}
#IBAction func minusTapped(theButton: UIButton) {
if operaterLabel.text == ""
{
operaterLabel.text = "-"
lastNumber = answerField.text
answerField.text = "0"
}
else
{
enterTapped(nil)
operaterLabel.text = "-"
}
}
#IBAction func clearTapped(AnyObject) {
answerField.text = "0"
operaterLabel.text = ""
lastNumber = ""
}
#IBAction func enterTapped(AnyObject?) {
var num1 = lastNumber.toInt()
var num2 = answerField.text.toInt()
if !num1 || !num2
{
showError()
return
}
var answer = 0
if operaterLabel.text == "-"
{
var answer = num1! - num2!
}
else if operaterLabel.text == "+"
{
var answer = num1! + num2!
}
else
{
showError()
return
}
answerField.text = "\(answer)"
}
func showError()
{
println("Ther was an error")
}
}
the error refers to the fact that you're accessing the parameter of an optional value when the optional value is set to nil (e.g. accessing answerField.text when answerField is nil), likely one of your two UILabels.
If the line operaterLabel.text == "" is throwing the exception, then your operaterLabel is nil. Verify that you have connected it successfully to the label in your Interface Builder file.
In my case, I was trying to access the labels in a function that I created which was used after the set of a variable.
var something: String {
didSet {
updateUI()
}
}
func updateUI() {
label.text = "Hello"
}
I solved it by:
var something: String
override func viewDidLoad() {
label.text = "hello"
}
My theory is that my function updateUI was accessed before the views and labels were created.
some times the problem that you have initiate view controller before present it like this:
let myViewController = MyViewController()
replace that by
let myViewController = self.storyboard?.instantiateViewController(withIdentifier: "storyboardID") as! MyViewController
check your outlets, I've had this before labels and buttons can just become dis connected (if for instance you have adjusted constraints ect)
a simple re connection can sometimes fix the issue
If you make sure the xib for your cell is no problem,
Then I occur this issue, my error was register the cell method :
1)
self.tableView.register(TerantInfoTabCell.self, forCellReuseIdentifier: "TerantInfoTabCell")
2)
self.tableView.register(UINib(nibName:"TerantInfoTabCell", bundle: nil), forCellReuseIdentifier: "TerantInfoTabCell")
I use the first method, there will appear the issue,then I use the 2) method replace the 1) , so there is no problem here.
I had the exact same error and spent quiet an amount of time debugging it. What #jmduke said is really the key: where does the error occur?
With my particular error, looking at operaterLabel.text == "" led me on the right path. I accessed the operaterLabel.text while the view was not yet fully initialized. In my particular case I set a variable from a different view during a segue and then acted upon that variable being set and updating a label inside the view. However the view was not completely initialized.
Thus my solution was to update the label inside the viewDidLoad() function.
I searched and searched trying to figure out how to solve my similar problem. As others mentioned, I was accessing UI elements before they were initialized. But figuring out why, was the difficult part. Spoiler --> I was using ProfileVC.swift and profileVC.xib
Even though I had all of my connections right in IB, from the parentVC I was calling
let newVC = ProfileVC()
profile.modalPresentationStyle = .custom
present(profile, animated: true, completion:nil)
Since I had different names (caplital 'P' in my swift file and lowercase 'p' in my xib), calling ProfileVC() didn't work as it didn't know to go to the xib I had made. Instead I had to use:
let newVC = ProfileVC.init(nibName: "profileVC", bundle: Bundle.main)
or just rename the xib to have a captial P and I could use my original code
Obviously this is hard to see in stackoverflow as you need to see what you are calling in the parent VC, the names of the files and IB. So hopefully this may be one solution to someone's problem out there even if it doesn't solve Arshia's problem.
That means your storyboard doesn't have a link to your IBOUTLET, please verify
I had this error and my problem was caused by adding a member (let's call it newProperty) to my model class, then trying to run a project that loaded data with NSCoder.decodeObjectForKey(newPropertyKey). During previous testing, I had saved objects without newProperty, so when the app tried to call decodeObjectForKey(newPropertyKey) on my old data, Xcode responded with this error message.
This error usually occurs because we try to change UILabel text after the view is loaded. Remember that UILabels once loaded in the view cannot be changed in any way they can only be set within viewdidload() function. You can check this by putting your text assigning code in the viewDidLoad() function which will set UILabels when loading the view, It will work.
But now if your application is built in such a way that it is setting UILabels after the view is loaded then the only solution is that you will need to create UILabels dynamically/Programatically where ever you want in the code and assign what ever you want because they will be created/instantiated with that text/label.
As #aircraft said you can register your cell this way :
let cellNib = UINib(nibName: "\(CellClass.self)", bundle: nil)
tableView.register(cellNib, forCellReuseIdentifier: "\(CellClass.self)")
this solved the problem with me.

Resources