Button set to nil Swift 2 - ios

I am developing an app using Swift 2 and Xcode 7. I have done the following code countless times and I was successful:
button.setTitle("New Title, forState: .Normal)
However, now I get an EXC_BAD_INSTRUCTION error. When I tried print(button), I got the error there. It says fatal error: unexpectedly found nil while unwrapping an Optional value. I am pretty sure that button is set to nil. I am connecting the button from the Main.Storyboard to the ViewContoller.swift What should I do?

There are three possibilities:
(1) The button outlet is not correctly connected in the storyboard.
(2) This ViewController instance is not the one in the storyboard.
(3) You're calling this code too soon (e.g. in prepareForSegue).

Outlets are usually declared as implicitly unwrapped optionals. (with an explanation point after the type.)
This means that it can be nil, but that you guarantee that before it's used, it will be set to a non-nil value.
You don't need to unwrap it, but referencing it if it IS nil will crash.
You should be able to use this form:
button?.setTitle("New Title, forState: .Normal)
That will skip the method call if button is nil.
(I say "should be able to" because I've been working with Objective-C for the past month and a half and my Swift is starting to get a little rusty.)

Related

UI label reading as nil? [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'm new to Xcode and was trying to make a simple code that would unhide a label when a button is pressed. I tried using the same code in a test project with one view controller and it worked just fine, but when I use it in a bigger project with 15+ view controllers I get the error. My outlets seem to be correct so I am not sure what is making the label nil.
Code that I used
Fixed it! Just manually initialized the object as hidden under drawing.
This error seem to be caused by the Outlet connecting problem to me,
I would suggest you to double check the storyboard & viewController connection.
To do so, you can go to your storyboard, and check on the all outlet connector in that scene.
If there are yellow sign, that mean that are the problems.
enter image description here
But if the outlet are correctly connect, try to move that line of code to ViewWillAppear, and see if the error still occurs.

IBOutlet in ScrollView producing nil

I have a simple UILabel, nothing special about it, in a UIView inside a UIScrollView. I can link it up to my ViewController.swift file just fine, and it doesn't crash on opening, but whenever I try to use the outlet, it produces a nil. I've been looking around for a solution and it seems as though you can't access an outlet inside a subview from the superview... but nothing has been exactly my situation, and none of the provided solutions work.
Here is the full error: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
The strange thing, though, is that I have another UILabel, seemingly the exact same, that works fine when I try to edit it. I do not know what is going on in the slightest here. How can I fix this?
"right click" no your label in storyboard and check if you don't have another outlet connected, maybe you deleted from code and connection is still there, other than that, you can delete the label from storyboard and recreate connections.
Try providing the #IBOutlet as not weak and try.
This is not the right way, but still let us see if it's working.

Swift: unexpectedly found nil while unwrapping an Optional value when setting delegate for UITextField object

Update: with 2 downvote of this question, I'd like to make this question a little bit useful to others - since I don't have the choice to delete it. The mistake I made was cut and paste codes which has interface outlet. As I was completely new at that time, I was assuming that when I copy and paste, the outlet link will be copied and pasted as well. Obviously it doesn't work that way.
I was writing a single-viewed app. It has one UITextField and one MKMapView. I want to do something when Return key is hit, so I basically followed
How to hide keyboard in swift on pressing return key?
But it does not fit well with my other codes. Any idea why it isn't working and how to fix it?
Make sure you connect your UITextField from StoryBoard to your searchText IBOutlet by control-dragging from the StoryBoard to the the searchText variable.
You have your outlet set up as implicitly unwrapped. That's the correct thing to do, but when your code executes the outlet must not be nil or your code will crash.
You probabably have a broken outlet link. Set a breakpoint and examine the outlet.
You can change your code to use an "if let" expression to prevent crashes. Search in the Swift language reference IBook for "Optional binding" to learn about it.
Edit:
The code might look like this:
if let requiredSerachText = searchtext
{
requiredSearchText.delegate = self
}

Fatal error: unexpectedly found nil while unwrapping an Optional values [duplicate]

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 6 years ago.
I was using an UICollectionView in Swift but I get when I try to change the text of the cell's label.
func collectionView(collectionView: UICollectionView!, numberOfItemsInSection section: Int) -> Int
{
return 5
}
func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell!
{
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("title", forIndexPath: indexPath) as TitleCollectionViewCell
// Next line: fatal error: unexpectedly found nil while unwrapping an Optional value
cell.labelTitle.text = "This is a title"
return cell
}
Does anyone know about this?
You can prevent the crash from happening by safely unwrapping cell.labelTitle with an if let statement.
if let label = cell.labelTitle{
label.text = "This is a title"
}
You will still have to do some debugging to see why you are getting a nil value there though.
Almost certainly, your reuse identifier "title" is incorrect.
We can see from the UITableView.h method signature of dequeueReusableCellWithIdentifier that the return type is an Implicitly Unwrapped Optional:
func dequeueReusableCellWithIdentifier(identifier: String!) -> AnyObject! // Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one.
That's determined by the exclamation mark after AnyObject:
AnyObject!
So, first thing to consider is, what is an "Implicitly Unwrapped Optional"?
The Swift Programming Language tells us:
Sometimes it is clear from a program’s structure that an optional will
always have a value, after that value is first set. In these cases, it
is useful to remove the need to check and unwrap the optional’s value
every time it is accessed, because it can be safely assumed to have a
value all of the time.
These kinds of optionals are defined as implicitly unwrapped
optionals. You write an implicitly unwrapped optional by placing an
exclamation mark (String!) rather than a question mark (String?) after
the type that you want to make optional.
So, basically, something that might have been nil at one point, but which from some point on is never nil again. We therefore save ourselves some bother by taking it in as the unwrapped value.
It makes sense in this case for dequeueReusableCellWithIdentifier to return such a value. The supplied identifier must have already been used to register the cell for reuse. Supply an incorrect identifier, the dequeue can't find it, and the runtime returns a nil that should never happen. It's a fatal error, the app crashes, and the Console output gives:
fatal error: unexpectedly found nil while unwrapping an Optional value
Bottom line: check your cell reuse identifier specified in the .storyboard, Xib, or in code, and ensure that it is correct when dequeuing.
Check if the cell is being registered with self.collectionView.registerClass(cellClass: AnyClass?, forCellWithReuseIdentifier identifier: String). If so, then remove that line of code.
See this answer for more info:
Why is UICollectionViewCell's outlet nil?
"If you are using a storyboard you don't want to call this. It will overwrite what you have in your storyboard."
I don't know is it bug or something but your labels and other UIs does not initialized automatically when you use custom cell. You should try this in your UICollectionViewController class. It worked for me.
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "<WhateverYourNibName>", bundle: nil)
self.collectionView.registerNib(nib, forCellReuseIdentifier: "title")
}
Replace this line
cell.labelTitle.text = "This is a title"
with
cell.labelTitle?.text = "This is a title"
I got his error when i was trying to access UILabel. I forgot to connect the UILabel to IBOutlet in Storyboard and that was causing the app to crash with this error!!
I was having this issue as well and the problem was in the view controllers. I'm not sure how your application is structured, so I'll just explain what I found. I'm pretty new to xcode and coding, so bear with me.
I was trying to programmatically change the text on a UILabel. Using "self.mylabel.text" worked fine until I added another view controller under the same class that didn't also include that label. That is when I got the error that you're seeing. When I added the same UILabel and connected it into that additional view controller, the error went away.
In short, it seems that in Swift, all view controllers assigned to the same class have to reference the code you have in there, or else you get an error. If you have two different view controllers with different code, assign them to different classes. This worked for me and hopefully applies to what you're doing.
fatal error: unexpectedly found nil while unwrapping an Optional value
Check the IBOutlet collection , because this error will have chance to unconnected uielement object usage.
:) hopes it will help for some struggled people .
I searched around for a solution to this myself. only my problem was related to UITableViewCell Not UICollectionView as your mentioning here.
First off, im new to iOS development. like brand new, sitting here trying to get trough my first tutorial, so dont take my word for anything. (unless its working ;) )
I was getting a nil reference to cell.detailTextLabel.text - After rewatching the tutorial video i was following, it didnt look like i had missed anything. So i entered the header file for the UITableViewCell and found this.
var detailTextLabel: UILabel! { get } // default is nil. label will be created if necessary (and the current style supports a detail label).
So i noticed that it says (and the current style supports a detail label) - Well, Custom style does not have a detailLabel on there by default. so i just had to switch the style of the cell in the Storyboard, and all was fine.
Im guesssing your label should always be there?
So if your following connor`s advice, that basically means, IF that label is available, then use it. If your style is correctly setup and the reuse identifier matches the one set in the Storyboard you should not have to do this check unless your using more then one custom cell.
Nil Coalescing Operator can be used as well.
rowName = rowName != nil ?rowName!.stringFromCamelCase():""
I had the same problem on Xcode 7.3. My solution was to make sure my cells had the correct reuse identifiers. Under the table view section set the table view cell to the corresponding identifier name you are using in the program, make sure they match.
I was having the same issue and the reason for it was because I was trying to load a UIImage with the wrong name. Double-check .setImage(UIImage(named: "-name-" calls and make sure the name is correct.
Same message here, but with a different cause. I had a UIBarButton that pushed a segue. The segue lacked an identifier.

IBOutlet property returning "Can't unwrap Optional.None" error

I'm getting stuck on some code with the dreaded "Can't unwrap Optional.None" error in my code.
I'm following the Shutterbug code from the iTunes U Stanford university course.
This is the code given in Objective-C for one of the classes.
http://pastebin.com/LG2k3BBW
and what I've come up with in Swift;
http://pastebin.com/pGtSzu6z
After tracing the errors these lines in particular seem to be giving me the problems
self.scrollView.zoomScale = 1.0
and
self.image = nil
Any advice on what's going wrong here?
I had originally put all the setters in the ViewDidLoad function and was receiving the same error.
This line is called when you are preparing for segue:
ivc.imageURL = flickerFetcher.URLforPhoto(photo, format: FlickrFetcher.FlickrPhotoFormat.Large)
Which calls the setter on imageURL:
set {
self.startDownloadingImage()
}
startDownloadingImage() calls the setter on image which is where you get all of your errors:
set{
self.imageView.image = image
self.scrollView.zoomScale = 1.0
self.spinner.stopAnimating()
self.imageView.frame = CGRectMake(0, 0, image!.size.width, image!.size.height)
}
Since all of this is happening in prepareForSegue, the view controller hasn't been loaded at this point and all of the outlets are nil hence the can't unwrap Optional.none.
You need to restructure your program's logic so that it isn't trying to do stuff with outlets before they are loaded.
Check your outlets are connected. Outlets are defined as implicitly unwrapped Optionals, so you'd expect to see that error if you referred to a property that wasn't set (e.g. If the outlet was not connected)
I've downloaded your project and there was a problem with the outlets - the scrollview and spinner were kind of grayed out in Xcode. Here's how the scrollview and spinner showed up for me:
This means that the items are not installed for the currently selected size class. If you go to the attributes inspector for that view, make sure the Installed option is checked for the size classes you care about:
In your project, the top box (representing any size class) was not checked.
However, there are many more problems within the code, too numerous to go into in full detail in this answer. You have several issues which are causing problems, including (I did give up after a while):
Infinite loops in your property accessors - for example, the get closure for imageURL
Implementing set or willSet closures when you actually want didSet - for example, the willSet on the scrollView would be better as a didSet, or you should be using newValue instead of scrollView, because at the point of willSet, scrollView is still nil.
Setting a value of nil to your image property, then accessing it in the setter block for that property
Something odd going on in your downloading logic (at this point, I decided to call it a day, sorry)

Resources