So, I've been making a basic calculator. But I've run into an issue.
My code.
#IBAction func calculate(_ sender: UIButton) {
let stringExpression = resultLabel.text!
let expression = NSExpression(format: stringExpression)
let result = expression.expressionValue(with: nil, context: nil) as! NSNumber
resultLabel.text! = String(result.doubleValue) // Writes response on textLabel :D
}
The code above works. However, when a input such as 5++6 is entered it crashes my app. I'm not very sure how to deal with this.
The following error is shown when a invalid input is entered.
The error given.
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
I'm not sure how I could make it display "Error".
And this should work for any type of error.
You have to pass a valid expression to the NSExpression initialiser or else it will throw an exception. There is no Swift-only way to catch exceptions so the only possibility for you is to make sure only valid input can be generated.
Related
I'm creating a signup form with multiple view controllers as "pages" and I need the information from one view controller such as 'First name' and 'last name' or 'email address' to another view controller. I decided I'm going to use core data to save the strings and retrieve them from another view controller rather than create a global struct for every view controller (because it crashes every time I try and implement it). Heres my code:
#IBAction func nextBtnWasPressed(_ sender: Any) {
if firstNameText.text != "" && lastNameText.text != "" {
//Core Data User Information
var userInfo = UserInfo() // The Name of the Core Data Entity
var firstName: String = firstNameText.text!
userInfo.firstName = firstName
do {
try NSManagedObjectContext.save(firstName)//Need Fixing
} catch {
fatalError("Failure to save context: \(error)")
}
performSegue(withIdentifier: "toBirthdate", sender: self)
} else {
nextBtn.alpha = 0.5
}
}
Here is the error log : 'Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UserInfo setFirstName:]: unrecognized selector sent to instance 0x600001530e80'
Full error log: View Here
Well, at first I was going to give the obvious answer which is that, in your Core Data data model, your UserInfo entity does not have a firstName attribute.
That's still possible, but then I looked at the full transcript you posted and saw that, a couple hundred microseconds before this error is another error:
Failed to call designated initializer on NSManagedObject class 'UserInfo'
I suspect this error indicates that you have initialized your managed object with init(). This is a common mistake of first-time Core Data users. Ensure that you are initializing your UserInfo object like this:
let userInfo = UserInfo.init(entity: entityDescription, insertInto: context);
or if your deployment target is iOS 10 or later, you can use the newer cleaner method:
let userInfo = UserInfo.init(context: context)
So far when after completing the username and password fields in my SignInViewController.
This is what the code looks like:
Code from SignInViewControllerExtension class
func startPasswordAuthentication() -> AWSCognitoIdentityPasswordAuthentication {
return self as! AWSCognitoIdentityPasswordAuthentication
}
My SignInViewControllerExtensions throws a Thread 1: Signal SIGABRT error with the following message in the debug area:
Could not cast value of type 'Elixr.SignInViewController' (0x1001460a8) to 'AWSCognitoIdentityPasswordAuthentication' (0x100134468).
You're probably trying to assign Elixr.SignInViewController as AWSCognitoIdentityPasswordAuthentication somewhere. But I can't say more without looking at the actual code.
But I'm guessing it's going to look something like this...
let someVc = SignInViewController(args_here) as! AWSCognitoIdentityPasswordAuthentication
The as! above is trying to force cast something that is not AWSCognito... so the code is going to crash.
I'm having troubles implementing the share extension in an application. I'm using swift 3, xcode8.
override func configurationItems() -> [Any]! {
// To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
let item = SLComposeSheetConfigurationItem();
item?.title = "Test";
item?.value = "Value";
item?.tapHandler = self.show;
return [item]
}
func show() {
print("TEST");
}
When I add that code to configure the items, I get the exception :
2016-09-19 09:22:20.623471 ARShareExtension[10583:675495] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue setChangeObserver:]: unrecognized selector sent to instance 0x17025af40'
I don't know what is wrong, I'm doing it as described in the apple developer site. I would appreciate if someone could help me :) thanks
A bit late, but if anyone still has problems with this, SLComposeSheetConfigurationItem() is now returning an Optional for some reason, but the return value is supposed to be an array of non-optional items, so you can do either
let item = SLComposeSheetConfigurationItem()!
or
guard let item = SLComposeSheetConfigurationItem() else { return nil }
I am integrating IDMPhotoBrowser in my Swift Project.
I have created a bridging header and I have imported IDMPhotoBrowser.
#import <IDMPhotoBrowser.h>
In my view controller:
class ViewController: UIViewController, IDMPhotoBrowserDelegate {
override func viewDidLoad() {
super.viewDidLoad()
var photoBro = IDMPhotoBrowser(photos: imagesArray)
photoBro.delegate = self
presentViewController(photoBro, animated: false, completion: nil)
}
But when it is executed, I get the following error
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString unloadUnderlyingImage]: unrecognized selector sent to instance 0x165d6870'
In IDMPhotoBrowser Library, I found this function in IDMPhoto.m
// Release if we can get it again from path or url
- (void)unloadUnderlyingImage {
_loadingInProgress = NO;
if (self.underlyingImage && (_photoPath || _photoURL)) {
self.underlyingImage = nil;
}
}
From the error it looks like it is expecting to do something to an array of IDMPhotos but instead has an array of strings...are you passing the right kind of array to the constructor?
As #GoatInTHeMachine pointed, I was not passing the right kind of array.
But as I wanted to pass the imageURLs, I had to change the constructor.
The following worked for me:
var photoBro = IDMPhotoBrowser(photoURLs: imagesArray)
I cannot build my project due to an error(Segmentation Fault 11). With commenting things out, I found that the error is thrown by this line:
typealias functionType = ([Expression], [String: NSNumber], inout AnyObject) -> Expression!;
If I remove the typealias and use the raw type instead, the error gets still thrown, so the mistake is probably not the typealias, but the closure.
Edit:
If I replace the type Expression with AnyObject the error gets still thrown. But if I just declare the typealias, I can use it for a global variable but not for a member variable.
I also got this error (following an online tutorial), I removed all the code I entered before to get this error and the problem persist, it seems to me as the project was corrupted. I'm not an expert so please take this report with caution.
This is happened just after appeared an error HUD telling sourceKitService Crashed...
The probably offending code was this one:
override func viewWillAppear(animated: Bool) {
if var storedtoDoItems: AnyObject! = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") {
toDoItems = []
for var i = 0; i < storedtoDoItems.count; ++i {
toDoItems.append(storedtoDoItems[i] as NSString)
}
println(storedtoDoItems)
}
taskTable.reloadData()
}