Instance Method インスタンスメソッド

perform(_:)

Sends a specified message to the receiver and returns the result of the message.

Declaration 宣言

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

Parameters パラメータ

aSelector

A selector identifying the message to send. The message should take no arguments. If aSelector is NULL, an invalidArgumentException is raised.

Return Value 戻り値

An object that is the result of the message.

Discussion 解説

Calling the perform(_:) method is equivalent to sending the aSelector message directly to the receiver, which you do in Swift using the dot syntax. For example, the following both do the same thing if anObject is an instance of MyObject:


let aClone = anObject.copy()
let aClone = anObject.perform(#selector(MyObject.copy)).takeRetainedValue()

The perform(_:) method allows you to send messages that aren’t determined until run-time. This means that you can pass a variable selector as the argument:


let aSelector = findTheAppropriateSelectorForTheCurrentSituation()
let returnedObject = anObject.perform(aSelector).takeUnretainedValue()

But use caution when doing this. The perform(_:) method returns an implicitly unwrapped optional unmanaged pointer to an AnyObject instance (Unmanaged<AnyObject>!). Because it knows nothing about the return value at compile-time, it is up to you to decide how to bring the instance into Swift’s memory management scheme.

Usually, a caller is not responsible for the memory of a returned instance, in which case you use takeUnretainedValue(), as shown above. However, for any of the creation methods, such as copy(), the caller is responsible, and you use takeRetainedValue() instead. See Memory Management Policy in Advanced Memory Management Programming Guide for a description of ownership expectations.

For more information about using selectors in Swift and alternatives to the perform(_:) function, read Selectors in Using Swift with Cocoa and Objective-C (Swift 4.1).

See Also 参照

Sending Messages メッセージ送信