LeonSaber LeonSaber - 1 year ago 109
iOS Question

IOS what is wrong for my code? Got "Thread 1: EXC_BAD_ INSTRUCTION(code=EXC_I386_INVOP,subcode=0x0)"

My code got the error, but I do not know what is wrong with my code, please give me some help, thanks so much.

Thread 1: EXC_BAD_ INSTRUCTION(code=EXC_I386_INVOP,subcode=0x0)
Error "fatal error: unexpectedly found nil while unwrapping an Optional value"

my code is :

let insertSQL = "INSERT INTO CONTACTS (location, reason, descri) VALUES ('\(location.text!)', '\(reason.text!)', '\(descri.text!)')" //Thread 1: EXC_BAD_ INSTRUCTION(code=EXC_I386_INVOP,subcode=0x0)

Answer Source

In order to access an optional’s value (if it has one at all), you need to unwrap it. An optional value can be unwrapped safely or forcibly. If you force-unwrap an optional, and it didn't have a value, your program will crash with the above message.

This crash can occur with two different kinds of force-unwrap:

1. Explicit Force Unwrapping

This is done with the ! operator on an optional.

For example:

let anOptionalString: String?
print(anOptionalString!) // <- CRASH

As anOptionalString is nil here, you will get a crash on the line where you force unwrap it.

2. Implicitly Unwrapped Optionals

These are defined with a !, rather than a ? after the type.

var optionalDouble: Double!  // this value is implicitly unwrapped wherever it's used

These optionals are assumed to contain a value. Therefore whenever you access an implicitly unwrapped optional, it will automatically be force unwrapped for you. If it doesn’t contain a value, it will crash.

print(optionalDouble) // <- CRASH

In order to work out which variable caused the crash, you can hold while clicking to show the definition, where you might find the optional type.

for more details go through this image

IBOutlets, in particular, are usually implicitly unwrapped optionals. This is because your xib or storyboard will link up the outlets at runtime, after initialization. You should therefore ensure that you’re not accessing outlets before they're loaded in. You also should check that the connections are correct in your storyboard/xib file, otherwise the values will be nil at runtime, and therefore crash when they are implicitly unwrapped.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download