Falling through to super.validateMenuItem(:) generates Swift exception - swift

I have a class, MyViewController, with several actions which are triggered from menu items.
class MyViewController: NSViewController { … }
The actions are connected to first responder in IB. Actions look like this:
#IBAction func removeSelectedItems(_ sender: AnyObject) {
arrayController.remove(contentsOf: arrayController.selectedObjects)
}
validateMenuItem(:) code looks like this:
override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
let selection = arrayController.selectedObjects
if (menuItem.action == #selector(removeSelectedItems(_:))) {
return selection!.count > 0
}
return super.validateMenuItem(menuItem)
}
When I include the actions in the if() list, everything is fine. But if I don't, and validateMenuItem(:) falls through to super, I get an exception:
[MyApp.MyViewController validateMenuItem:]: unrecognized selector sent to instance 0x618000165ac0
If I instead return false at the end of the method, there's no exception.
This happens when validateMenuItem(:) is called, e.g. when the menu is opened. In spite of this, though, the action is triggered when the item is selected.
Am I wrong to be calling super at the end of the method? I would expect the responder chain to be queried until a match was found, not an exception claiming I didn't implement a method which I clearly did!

Am I wrong to be calling super at the end of the method
Yes. Neither NSViewController nor any of its superclasses implements validateMenuItem. Despite the override in Swift, it is not actually inherited. It is injected in Objective-C by an informal protocol (NSMenuValidation). [The Swift compiler doesn't understand that kind of trickery; hence the override despite the fact that we are not overriding anything.]
See https://forums.developer.apple.com/thread/46772

Related

Selector to method inside singleton

This sounds like a stupid question, but I have been trying to find a solution for hours now, and I still don't know what to do. I am using Swift 3.0, and I am having an issue calling a method inside a singleton class from a selector inside another class. My singleton class is as follows:
class Singleton : NSObject {
static let sharedInstance = Singleton()
private override init() {} // defeats instantiation
func myAction() {
// do something useful...
}
}
Then, here is the class from which I am calling the method contained in the Singleton:
class StatusBarPresenter {
func addItemsToMenu(menu: NSMenu) {
...
menu.insertItem(withTitle: "Disconnect this network",
action: #selector(Singleton.sharedInstance.myAction),
keyEquivalent: "D", at: 4)
...
}
}
Xcode doesn't complain about the code... it compiles without any errors or warnings, but the selector doesn't work. The UIMenuItem that I add to the menu is disabled, which means that the selector is not working. If the selector instead calls a method inside the class, everything works fine just as usual. This is a screenshot of what I am getting:
Thanks to Martin R. for pointing out that in my code I was not setting an explicit target for the UIMenuItem, leading to it being nil and ultimately self.
The following line added to the addItemsToMenu function after the call to insertItem solves the problem:
menu.item(at: 4)?.target = Singleton.sharedInstance

In Swift, can you write an extension which returns a typed instance of the class the extension is on?

This is one of those things that seems simple enough, but doesn't work as you'd expect.
I'm working on a 'fluent/chaining'-style API for my classes to allow you to set properties via functions which can be chained together so you don't have to go crazy with initializers. Plus, it makes it more convenient when working with functions like map, filter and reduce which share the same kind of API.
Consider this RowManager extension...
extension RowManager
{
#discardableResult
public func isVisible(_ isVisible:Bool) -> RowManager
{
self.isVisible = isVisible
return self
}
}
This works exactly as one would expect. But there's a problem here... if you're working with a subclass of RowManager, this downcasts the object back to RowManager, losing all of the subclass-specific details.
"No worries!" I thought. "I'll just use Self and self to handle the type!" so I changed it to this...
extension RowManager
{
#discardableResult
public func isVisible(_ isVisible:Bool) -> Self // Note the capitalization representing the type, not instance
{
self.isVisible = isVisible
return self // Note the lowercase representing the instance, not type
}
}
...but that for some reason won't even compile giving the following error...
Command failed due to signal: Segmentation fault: 11
UPDATE
Doing more research, this seems to be because our code both is in, and also uses, dynamic libraries. Other questions here on SO also talk about that specific error in those cases. Perhaps this is a bug with the compiler because as others have correctly pointed out, this code works fine in a stand-alone test but as soon as the change is made in our code, the segmentation fault shows up.
Remembering something similar with class functions that return an instance of that type, I recalled how you had to use a private generic function to do the actual cast, so I tried to match that pattern with the following...
extension RowManager
{
#discardableResult
public func isVisible(_ isVisible:Bool) -> Self // Note the capitalization
{
self.isVisible = isVisible
return getTypedSelf()
}
}
private func getTypedSelf<T:RowManager>() -> T
{
guard let typedSelfInstance = self as? T
else
{
fatalError() // Technically this should never be reachable.
}
return typedSelfInstance
}
Unfortunately, that didn't work either.
For reference, here's the class-based code I attempted to base that off of (className is another extension that simply returns the string-representation of the name of the class you called it on)...
extension UITableViewCell
{
/// Attempts to dequeue a UITableViewCell from a table, implicitly using the class name as the reuse identifier
/// Returns a strongly-typed optional
class func dequeue(from tableView:UITableView) -> Self?
{
return self.dequeue(from:tableView, withReuseIdentifier:className)
}
/// Attempts to dequeue a UITableViewCell from a table based on the specified reuse identifier
/// Returns a strongly-typed optional
class func dequeue(from tableView:UITableView, withReuseIdentifier reuseIdentifier:String) -> Self?
{
return self.dequeue_Worker(tableView:tableView, reuseIdentifier:reuseIdentifier)
}
// Private implementation
private class func dequeue_Worker<T:UITableViewCell>(tableView:UITableView, reuseIdentifier:String) -> T?
{
return tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) as? T
}
}
At WWDC Apple confirmed this was a Swift compiler issue that something else In our codebase was triggering, adding there should never be a case where you get a Seg11 fault in the compiler under any circumstances, so this question is actually invalid. Closing it now, but I will report back if they ever address it.

How should I name a delegate method that returns a "continue" flag?

In my Swift code, I have a few methods that look like this:
protocol EditorDelegate {
// ...
func didStartSearch(query: String) -> Bool
}
class Editor: UIViewController {
func search(sender: AnyObject) {
let wasHandled = self.delegate?.didStartSearch(query) ?? false
if !wasHandled {
// do default searching behavior
}
}
}
This works, but it's not self-documenting. The didStartSearch method doesn't really communicate that it's returning a flag indicating whether the default behavior should be skipped.
What are some good options for handling this?
I tried to think of a better way to name the delegate function, below is what I came up with that makes the most sense to me. Enums are very powerful in swift, using them can make code more understandable at a glance. Also I like to think of things in terms of different states, which can be clearly defined with enums.
enum SearchStatus {
case Ready
case Processing
case Complete(result: String)
}
protocol EditorDelegate: class {
func statusForSearch(with query: String) -> SearchStatus
}
class Editor: UIViewController {
weak var delegate: EditorDelegate?
func search(sender: AnyObject) {
let query = "some input.."
guard let status = delegate?.statusForSearch(with: query) else {
// delegate not set
return
}
switch status {
case .Ready:
// actually do your search
break
case .Processing:
// search in progress
break
case .Complete(let result):
// do something with result
print("result = \(result)")
break
}
}
}
Think about the relationship between the delegating object and the object being delegated to, and the "message" (in high-level semantics, not just code) that a call to the delegate method is about. That is, does a delegate method call mean, "hey, in case you're interested, this thing happened," or, "this thing happened, what should I do about it?". If the delegate returns a value to the delegating object, you're probably in the second category.
Per Coding Guidelines for Cocoa, delegate methods should:
Start by identifying the delegating object (e.g. the tableView in tableView:didSelectRow: or the window in windowWillClose:). This is important because delegation can be a many-to-one relationship — if you have a delegate property (or setDelegate method) on one class, there's nothing preventing one object from being the delegate of many others, and indeed that can be a useful pattern for whoever adopts your delegate protocol.
If the method asks something of the delegate, either name the thing being asked (e.g. cellForRowAtIndexPath), or for Boolean conditions, describe the consequence of a positive value — this usually involves language like "should" (e.g. windowShouldClose, tableView:shouldSelectRowAtIndexPath:).
In your case, it's not entirely clear what "should" happen as a result of the delegate returning true or false, but here's a guess:
protocol EditorDelegate {
func editor(_ editor: Editor, shouldShowDefaultResultsForSearch query: String) -> Bool
}
The use of return flags is often considered problematic for many reasons. See this link for one of many explanations of the arguments for and against. Nevertheless, one solution that might help in this case would be to use a typealias.
typealias useDefaultBehaviour = Bool
protocol EditorDelegate {
func didStartSearch(query: String) -> useDefaultBehaviour
}

How do I resolve "ambiguous use of" compile error with Swift #selector syntax?

[NOTE This question was originally formulated under Swift 2.2. It has been revised for Swift 4, involving two important language changes: the first method parameter external is no longer automatically suppressed, and a selector must be explicitly exposed to Objective-C.]
Let's say I have these two methods in my class:
#objc func test() {}
#objc func test(_ sender:AnyObject?) {}
Now I want to use Swift 2.2's new #selector syntax to make a selector corresponding to the first of these methods, func test(). How do I do it? When I try this:
let selector = #selector(test) // error
... I get an error, "Ambiguous use of test()." But if I say this:
let selector = #selector(test(_:)) // ok, but...
... the error goes away, but I'm now referring to the wrong method, the one with a parameter. I want to refer to the one without any parameter. How do I do it?
[Note: the example is not artificial. NSObject has both Objective-C copy and copy: instance methods, Swift copy() and copy(sender:AnyObject?); so the problem can easily arise in real life.]
[NOTE This answer was originally formulated under Swift 2.2. It has been revised for Swift 4, involving two important language changes: the first method parameter external is no longer automatically suppressed, and a selector must be explicitly exposed to Objective-C.]
You can work around this problem by casting your function reference to the correct method signature:
let selector = #selector(test as () -> Void)
(However, in my opinion, you should not have to do this. I regard this situation as a bug, revealing that Swift's syntax for referring to functions is inadequate. I filed a bug report, but to no avail.)
Just to summarize the new #selector syntax:
The purpose of this syntax is to prevent the all-too-common runtime crashes (typically "unrecognized selector") that can arise when supplying a selector as a literal string. #selector() takes a function reference, and the compiler will check that the function really exists and will resolve the reference to an Objective-C selector for you. Thus, you can't readily make any mistake.
(EDIT: Okay, yes you can. You can be a complete lunkhead and set the target to an instance that doesn't implement the action message specified by the #selector. The compiler won't stop you and you'll crash just like in the good old days. Sigh...)
A function reference can appear in any of three forms:
The bare name of the function. This is sufficient if the function is unambiguous. Thus, for example:
#objc func test(_ sender:AnyObject?) {}
func makeSelector() {
let selector = #selector(test)
}
There is only one test method, so this #selector refers to it even though it takes a parameter and the #selector doesn't mention the parameter. The resolved Objective-C selector, behind the scenes, will still correctly be "test:" (with the colon, indicating a parameter).
The name of the function along with the rest of its signature. For example:
func test() {}
func test(_ sender:AnyObject?) {}
func makeSelector() {
let selector = #selector(test(_:))
}
We have two test methods, so we need to differentiate; the notation test(_:) resolves to the second one, the one with a parameter.
The name of the function with or without the rest of its signature, plus a cast to show the types of the parameters. Thus:
#objc func test(_ integer:Int) {}
#nonobjc func test(_ string:String) {}
func makeSelector() {
let selector1 = #selector(test as (Int) -> Void)
// or:
let selector2 = #selector(test(_:) as (Int) -> Void)
}
Here, we have overloaded test(_:). The overloading cannot be exposed to Objective-C, because Objective-C doesn't permit overloading, so only one of them is exposed, and we can form a selector only for the one that is exposed, because selectors are an Objective-C feature. But we must still disambiguate as far as Swift is concerned, and the cast does that.
(It is this linguistic feature that is used — misused, in my opinion — as the basis of the answer above.)
Also, you might have to help Swift resolve the function reference by telling it what class the function is in:
If the class is the same as this one, or up the superclass chain from this one, no further resolution is usually needed (as shown in the examples above); optionally, you can say self, with dot-notation (e.g. #selector(self.test), and in some situations you might have to do so.
Otherwise, you use either a reference to an instance for which the method is implemented, with dot-notation, as in this real-life example (self.mp is an MPMusicPlayerController):
let pause = UIBarButtonItem(barButtonSystemItem: .pause,
target: self.mp, action: #selector(self.mp.pause))
...or you can use the name of the class, with dot-notation:
class ClassA : NSObject {
#objc func test() {}
}
class ClassB {
func makeSelector() {
let selector = #selector(ClassA.test)
}
}
(This seems a curious notation, because it looks like you're saying test is a class method rather than an instance method, but it will be correctly resolved to a selector nonetheless, which is all that matters.)
I want to add a missing disambiguation: accessing an instance method from outside the class.
class Foo {
#objc func test() {}
#objc func test(_ sender: AnyObject?) {}
}
From the class' perspective the full signature of the test() method is (Foo) -> () -> Void, which you will need to specify in order to get the Selector.
#selector(Foo.test as (Foo) -> () -> Void)
#selector(Foo.test(_:))
Alternatively you can refer to an instance's Selectors as shown in the original answer.
let foo = Foo()
#selector(foo.test as () -> Void)
#selector(foo.test(_:))
In my case (Xcode 11.3.1) the error was only when using lldb while debugging. When running it works properly.

Can a Swift class be extended multiple times with the same methods?

I am designing a framework that uses protocols and extensions to allow for third-parties to add support for my framework to their existing classes.
I'd also like to include some built-in extensions for known classes like UIView, but I don't want to prevent users from defining their own additional support for the same classes.
My question is is there any way that I can extend the same class twice, and override the same (protocol) method in that class both times, while still having some way to call the other if the first one fails.
Elaboration: I really have three goals here I want to achieve:
I want to allow users of my framework to provide their own extensions for their own (or any) UIView subclasses.
I also need some way to allow general behavior that can apply to all UIViews as a fallback option (i.e. if the specific class extension can't handle it, fall back on the generic UIView extension).
I'd also like to separate out my own implementation, by providing some built-in generic view handling, but in such a way that it doesn't prevent third parties from also defining their own additional generic handling. (If I can't do this, it's not a big deal, the first two parts are the most important.)
I have part 1 working already. The problem is how to get this fallback behavior implemented. If I do it all with extensions, the subclass will override the superclass's implementation of the protocol method. It could call super.method, but I'd like to avoid putting that responsibility on the subclass (in case the author forgets to call super).
I'd like to do this all from the framework code: first, call the object's protocol method. If it returns false, I'd like to somehow call the generic UIView handler.
Now that I'm typing it all out, I'm wondering if I can just use a different method for the generic fallback and be done with it. I just figured it would be elegant if I could do it all with one method.
No! It can't be extended multiple times.
extension Int {
var add: Int {return self + 100} // Line A
}
extension Int {
var add: Int {return self + 105} //Line B
}
Doing so would create a compile time error ( on Line B) indicating: Invalid redeclaration of 'add'
Swift is a static typing language and helps you find these sorts of errors before runtime
In Objective-C you can write this and still not get an error, however the result would be undefined, because you wouldn't know which method gets loaded first during runtime.
Overriding a single protocol method twice in 2 separate extensions wouldn't work, because the protocol method names would collide. Once compiled, they're all just methods on the same class. With that in mind, perhaps put all the protocol methods in their own extension & call them from within the other ones?
The following could be one general option. Could get messy if you decide to keep adding additional extension functionality.
class baseClass {
//stuff
}
extension baseClass: myProtocol {
override func myProtocolMethod(args) -> returnType {
//Repeat this in a separate extension & your method names collide
var status: Bool
//protocol method code sets status as appropriate...
return status = true ? optOne(status) : optTwo(status)
}
func optOne(status:Bool) -> returnType{
//do the 'true' thing
return returnType
}
func optTwo(status:Bool) -> returnType{
//do the 'false' thing
return returnType
}
}
extension baseClass {
var oneExtension = myProtocolMethod(someArg)
}
extension baseClass {
var twoExtension = myProtocolMethod(someArg)
}
I realize this Question is over a year old and the original poster has probably moved on to other things, but I'd like to share an idea anyways and perhaps get some feedback.
You say that you want a method that can be overwritten multiple times. The short answer, like many in this thread have given is no, but the long answer is yes.
We can solve the issue with a bit of generic magic.
class MyView: UIView {
var customizer: MyProtocol<MyView> = Defaults()
func willCallCustomizer() {
customizer.coolMethod(self)
}
}
// Use this class as if it were a protocol
class MyProtocol<T: UIView>: NSObject {
func coolMethod(_ view: T) {}
}
// Class inherits from the "protocol"
class Defaults: MyProtocol<MyView> {
override func coolMethod(_ view: MyView) {
// Some default behavior
}
}
/// on the clients end...
class CustomerCustomizer: MyProtocol<MyView> {
override func coolMethod(_ view: MyView) {
// customized behavior
}
}
So if the client wants to use their own customizer they can just set it, otherwise it will just use the default one.
myViewInstance.customizer = CustomerCustomizer()
The benefit of this approach is that the client can change the customizer object as many times as they want. Because MyProtocol is generic, it may be used for other UIView's as well; thus fulfilling the role of a protocol.