var error: NSError? = nil
return app.managedObjectContext!.save(&error)
It said "Cannot force unwrap value of non-optional type 'NSManagedObjectContext'"
And if i delete '!'
It said "'&' used with non-in out argument of type '()'"
And finally i delete '&'
It said "Argument passed to call that takes no arguments"
I feel hopeless.
You need to use the new syntax:
do
{
try app.managedObjectContext.save()
} catch let error as NSError {
print(error)
}
Related
I used this method very much in Swift 1.2: NSURLConnection.sendSynchronousRequest(:_:_:_) but this is apparently deprecated in iOS9. It still works however but now it uses the new Swift 2.0 Error Handling and I don't know how I will get the error message if it fails, ex. if time runs out.
I know I have to put it into a do-catch and then say try before the metho but I dont know how to catch the error message.
do {
let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
return data
}
catch _ {
return nil
}
Before I used NSError and then its description property, but now I have no clue.
Use automatic error variable, and you can cast it to NSError if you wish:
catch {
let nsError = error as NSError
print(nsError.localizedDescription)
}
You can now throw any object inheriting ErrorType, and provide custom handling in the catch sentence. You can also cast the error to NSError to access localizedDescription for handling third party errors.
Casting an enum ErrorType will produce a NSError with domain equal to the enum name, code equal to the enum value and an auto-generated localizedDescription with the following format:
The operation couldn’t be completed. (DOMAIN error CODE.)
For example, the following code:
enum AwfulError: ErrorType {
case Bad
case Worse
case Terrible
}
func throwingFunction() throws {
throw AwfulError.Worse
}
do {
try throwingFunction()
}
catch AwfulError.Bad {
print("Bad error")
}
catch let error as NSError {
print(error.localizedDescription)
}
Will print
The operation couldn’t be completed. (AwfulError error 1.)
Despite the question title specifying Swift 2, this answer is for Swift 3.
As #redent84 points out, since Swift 2 an Error object may be a home-made one. Here's a method I wrote to analyze and print the default error object available in a "catch" statement that doesn't specify any specific error type:
// Method to print an unknown Error type object to the system output.
static func printCaughtError(_ unknownError : Error) {
let objectDescription = String(describing: unknownError)
let localizedDescription = unknownError.localizedDescription
if localizedDescription != "" {
if localizedDescription.contains(objectDescription) {
print(localizedDescription)
return
}
if !objectDescription.contains(localizedDescription) {
print(objectDescription + ": " + localizedDescription)
return
}
}
print(objectDescription)
}
Then you can call it like this:
catch {
printCaughtError(error)
}
How to get the error message that is inside userInfo:
let errorMessage = (error as NSError).userInfo["message"] as? String
var input = AVCaptureDeviceInput(device: backCamera)
The error message i get says call can throw, but it is not marked with 'try' and the error is not handled.
also I have this line of code
if ((error == nil && captureSession?.canAddInput(input)) != nil)
Optional type 'Bool' cannot be used as a boolean; test for "!=nil" instead.
Auto Correct is on but for the second line when i click fix it just rewrites the same line of code and adds another "!=nil".
You are getting the error that says
this call can throw, but it is not marked with try and the error is not handled.
because you did not catch the exceptions that could be thrown. Instead, you should be using this
var error: NSError?
do{
let input = try AVCaptureDeviceInput(device: backCamera)
}
catch let myError as NSError{
error = myError
}
The second error is because captureSession?.canAddInput(input) returns an optional Bool value. To fix this, you should be using (captureSession?.canAddInput(input) ?? false), which effectively turns nil values into false.
if(error == nil && (captureSession?.canAddInput(input) ?? false))
A better way to do this would be to put it all in the do-catch statement
do{
let input = try AVCaptureDeviceInput(device: backCamera)
if((captureSession?.canAddInput(input) ?? false)){
//your code
}
}
catch var error as NSError{
//handle the NSError 'error'
}
For your first line, I believe all you have to do is surround it with a
do{
try //statement
}catch {
}
For the second statement, I believe the reason why the compiler is complaining is because you are trying to evaluate a type Bool for nil or not, try simply having
(error == nil && captureSession?.canAddInput(input))
Using Xcode 7 and swift 2.0 if get the following error on the context?.save(nil).
Any help is appreciated
"cannot use optional chaining on non-optional value of type 'NSManagedObjectContext'
func newItem() {
let context = self.context
let ent = NSEntityDescription.entityForName("CallList", inManagedObjectContext: context)
let nItem = CallList(entity: ent!, insertIntoManagedObjectContext: context)
nItem.firstname = firstName.text
nItem.lastname = lastName.text
nItem.phonenumber = phoneNumber.text
context?.save(nil)
You get that error as your context variable is not optional so the ? is useless.
Also swift 2 introduced the do-catch construct to allow advanced error handling as you would do in other languages with try-catch, so functions with an error parameter such as save() of NSManagedObjectContext changed and have lost the error parameter and report errors as exceptions; so you should do
do {
try context.save()
} catch let error {
// Handle error stored in *error* here
}
If you don't want to handle the error you can do
do {
try context.save()
} catch {}
I used this method very much in Swift 1.2: NSURLConnection.sendSynchronousRequest(:_:_:_) but this is apparently deprecated in iOS9. It still works however but now it uses the new Swift 2.0 Error Handling and I don't know how I will get the error message if it fails, ex. if time runs out.
I know I have to put it into a do-catch and then say try before the metho but I dont know how to catch the error message.
do {
let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
return data
}
catch _ {
return nil
}
Before I used NSError and then its description property, but now I have no clue.
Use automatic error variable, and you can cast it to NSError if you wish:
catch {
let nsError = error as NSError
print(nsError.localizedDescription)
}
You can now throw any object inheriting ErrorType, and provide custom handling in the catch sentence. You can also cast the error to NSError to access localizedDescription for handling third party errors.
Casting an enum ErrorType will produce a NSError with domain equal to the enum name, code equal to the enum value and an auto-generated localizedDescription with the following format:
The operation couldn’t be completed. (DOMAIN error CODE.)
For example, the following code:
enum AwfulError: ErrorType {
case Bad
case Worse
case Terrible
}
func throwingFunction() throws {
throw AwfulError.Worse
}
do {
try throwingFunction()
}
catch AwfulError.Bad {
print("Bad error")
}
catch let error as NSError {
print(error.localizedDescription)
}
Will print
The operation couldn’t be completed. (AwfulError error 1.)
Despite the question title specifying Swift 2, this answer is for Swift 3.
As #redent84 points out, since Swift 2 an Error object may be a home-made one. Here's a method I wrote to analyze and print the default error object available in a "catch" statement that doesn't specify any specific error type:
// Method to print an unknown Error type object to the system output.
static func printCaughtError(_ unknownError : Error) {
let objectDescription = String(describing: unknownError)
let localizedDescription = unknownError.localizedDescription
if localizedDescription != "" {
if localizedDescription.contains(objectDescription) {
print(localizedDescription)
return
}
if !objectDescription.contains(localizedDescription) {
print(objectDescription + ": " + localizedDescription)
return
}
}
print(objectDescription)
}
Then you can call it like this:
catch {
printCaughtError(error)
}
How to get the error message that is inside userInfo:
let errorMessage = (error as NSError).userInfo["message"] as? String
I commonly see a pointer to an optional error variable being used, just like in this block of code:
if fileManager.fileExistsAtPath(path)
{
var error: NSError?
if !fileManager.removeItemAtPath(path, error: &error)
{
println("Error removing the file : \(error)")
}
}
Why do we do this?
The error parameter is an inout parameter, and can set the value of error rather than returning it from the function. Look up "inout" in Apple's iBook on Swift.