5

What is the use of -

func perform(_ aSelector: Selector!) -> unmanaged<AnyObject>!

in iOS?

  • To call a method of a class?
  • To add a selector method?
  • To add a class delegate?
  • To define a class? (I doubt it's this)

I was originally thinking that it it was to add a selector method, but after looking at it some more I think it may be "to call a method of a class." Selectors are used for target/action paradigms where I kick something off and when the event fires or finishes then it wants to fire off some kind of action method. In this example do I pass it a parameter of a selector function then at the end of this "perform" function, I am returning an unmanaged object of any type? Does that even make sense?

Thanks!

TSuperman
  • 83
  • 5
  • Are you referring to the method from `NSObjectProtocol` which is from the Objective-C runtime? – rmaddy Nov 14 '18 at 23:41
  • @rmaddy --> I don't know. This was asked on a quiz that I was taking and I didn't have any other information for this question. – TSuperman Nov 14 '18 at 23:49
  • @rmaddy -> If the method was referring to the NSObjectProtocol, would it have a different meaning or do something that I wouldn't normally expect? – TSuperman Nov 15 '18 at 00:01
  • 1
    Basically it's something you would very rarely, if ever, use in Swift. It should rarely be used directly any more in Objective-C. – rmaddy Nov 15 '18 at 00:03
  • 1
    Indeed this used to be forbidden in Swift, and even now should be avoided, as Swift provides better ways. See https://stackoverflow.com/questions/24158427/alternative-to-performselector-in-swift for example – matt Nov 15 '18 at 00:55

1 Answers1

3

In Swift this is basically useless. It's bridged from Objective-C, where it used to be very useful (before ARC), but now it's a bit tricky.

The point of it is to send a message by name and get a result. Generally speaking that translates to calling a method of that name.

Rob Napier
  • 250,948
  • 34
  • 393
  • 528
  • So basically this is "calling a method" and returning some data type? Not a nice way of doing it, but a long, obnoxious way of doing it? – TSuperman Nov 14 '18 at 23:44
  • 1
    It's only obnoxious in Swift. In ObjC, it's pretty elegant, and is the core tool used for all the target/action features like UIButton, NSTimer, and the like. – Rob Napier Nov 15 '18 at 00:02
  • Thanks! I have been writing more Swift code than Objective-C. – TSuperman Nov 15 '18 at 00:42
  • Is this method just short-hand for the ObjC runtime APIs like `class_getMethodImplementation(AnyClass?, Selector)`? – Alexander Nov 15 '18 at 01:37
  • 1
    @Alexander It's a wrapper around `objc_msgSend`. You can see the source code for it here: https://opensource.apple.com/source/objc4/objc4-723/runtime/NSObject.mm.auto.html – Rob Napier Nov 15 '18 at 13:46