AVAudioEngine

Struct AVAudioEngine 

Source
pub struct AVAudioEngine { /* private fields */ }
Available on crate feature AVAudioEngine only.
Expand description

An AVAudioEngine contains a group of connected AVAudioNodes (“nodes”), each of which performs an audio signal generation, processing, or input/output task.

Nodes are created separately and attached to the engine.

The engine supports dynamic connection, disconnection and removal of nodes while running, with only minor limitations:

  • all dynamic reconnections must occur upstream of a mixer
  • while removals of effects will normally result in the automatic connection of the adjacent nodes, removal of a node which has differing input vs. output channel counts, or which is a mixer, is likely to result in a broken graph.

By default, the engine is connected to an audio device and automatically renders in realtime. It can also be configured to operate in manual rendering mode, i.e. not connected to an audio device and rendering in response to requests from the client, normally at or faster than realtime rate.

See also Apple’s documentation

Implementations§

Source§

impl AVAudioEngine

Source

pub unsafe fn init(this: Allocated<Self>) -> Retained<Self>

Initialize a new engine.

On creation, the engine is by default connected to an audio device and automatically renders in realtime. It can be configured to operate in manual rendering mode through enableManualRenderingMode:format:maximumFrameCount:error:.

Source

pub unsafe fn attachNode(&self, node: &AVAudioNode)

Available on crate feature AVAudioNode only.

Take ownership of a new node.

Parameter node: The node to be attached to the engine.

To support the instantiation of arbitrary AVAudioNode subclasses, instances are created externally to the engine, but are not usable until they are attached to the engine via this method. Thus the idiom, without ARC, is:

// when building engine:
AVAudioNode *_player;    // member of controller class (for example)
...
_player = [[AVAudioPlayerNode alloc] init];
[engine attachNode: _player];
...
// when destroying engine (without ARC)
[_player release];
Source

pub unsafe fn detachNode(&self, node: &AVAudioNode)

Available on crate feature AVAudioNode only.

Detach a node previously attached to the engine.

If necessary, the engine will safely disconnect the node before detaching it.

Source

pub unsafe fn connect_to_fromBus_toBus_format( &self, node1: &AVAudioNode, node2: &AVAudioNode, bus1: AVAudioNodeBus, bus2: AVAudioNodeBus, format: Option<&AVAudioFormat>, )

Available on crate features AVAudioFormat and AVAudioNode and AVAudioTypes only.

Establish a connection between two nodes.

Parameter node1: The source node

Parameter node2: The destination node

Parameter bus1: The output bus on the source node

Parameter bus2: The input bus on the destination node

Parameter format: If non-nil, the format of the source node’s output bus is set to this format. In all cases, the format of the destination node’s input bus is set to match that of the source node’s output bus.

Nodes have input and output buses (AVAudioNodeBus). Use this method to establish one-to-one connections betweeen nodes. Connections made using this method are always one-to-one, never one-to-many or many-to-one.

Note that any pre-existing connection(s) involving the source’s output bus or the destination’s input bus will be broken.

Source

pub unsafe fn connect_to_format( &self, node1: &AVAudioNode, node2: &AVAudioNode, format: Option<&AVAudioFormat>, )

Available on crate features AVAudioFormat and AVAudioNode only.

Establish a connection between two nodes

This calls connect:to:fromBus:toBus:format: using bus 0 on the source node, and bus 0 on the destination node, except in the case of a destination which is a mixer, in which case the destination is the mixer’s nextAvailableInputBus.

Source

pub unsafe fn connect_toConnectionPoints_fromBus_format( &self, source_node: &AVAudioNode, dest_nodes: &NSArray<AVAudioConnectionPoint>, source_bus: AVAudioNodeBus, format: Option<&AVAudioFormat>, )

Available on crate features AVAudioConnectionPoint and AVAudioFormat and AVAudioNode and AVAudioTypes only.

Establish connections between a source node and multiple destination nodes.

Parameter sourceNode: The source node

Parameter destNodes: An array of AVAudioConnectionPoint objects specifying destination nodes and busses

Parameter sourceBus: The output bus on source node

Parameter format: If non-nil, the format of the source node’s output bus is set to this format. In all cases, the format of the destination nodes’ input bus is set to match that of the source node’s output bus

Use this method to establish connections from a source node to multiple destination nodes. Connections made using this method are either one-to-one (when a single destination connection is specified) or one-to-many (when multiple connections are specified), but never many-to-one.

To incrementally add a new connection to a source node, use this method with an array of AVAudioConnectionPoint objects comprising of pre-existing connections (obtained from outputConnectionPointsForNode:outputBus:) and the new connection.

Note that any pre-existing connection involving the destination’s input bus will be broken. And, any pre-existing connection on source node which is not a part of the specified destination connection array will also be broken.

Also note that when the output of a node is split into multiple paths, all the paths must render at the same rate until they reach a common mixer. In other words, starting from the split node until the common mixer node where all split paths terminate, you cannot have:

  • any AVAudioUnitTimeEffect
  • any sample rate conversion
Source

pub unsafe fn disconnectNodeInput_bus( &self, node: &AVAudioNode, bus: AVAudioNodeBus, )

Available on crate features AVAudioNode and AVAudioTypes only.

Remove a connection between two nodes.

Parameter node: The node whose input is to be disconnected

Parameter bus: The destination’s input bus to disconnect

Source

pub unsafe fn disconnectNodeInput(&self, node: &AVAudioNode)

Available on crate feature AVAudioNode only.

Remove a connection between two nodes.

Parameter node: The node whose inputs are to be disconnected

Connections are broken on each of the node’s input busses.

Source

pub unsafe fn disconnectNodeOutput_bus( &self, node: &AVAudioNode, bus: AVAudioNodeBus, )

Available on crate features AVAudioNode and AVAudioTypes only.

Remove a connection between two nodes.

Parameter node: The node whose output is to be disconnected

Parameter bus: The source’s output bus to disconnect

Source

pub unsafe fn disconnectNodeOutput(&self, node: &AVAudioNode)

Available on crate feature AVAudioNode only.

Remove a connection between two nodes.

Parameter node: The node whose outputs are to be disconnected

Connections are broken on each of the node’s output busses.

Source

pub unsafe fn prepare(&self)

Prepare the engine for starting.

This method preallocates many of the resources the engine requires in order to start. Use it to responsively start audio input or output.

On AVAudioSession supported platforms, this method may cause the audio session to be implicitly activated. Activating the audio session (implicitly or explicitly) may cause other audio sessions to be interrupted or ducked depending on the session’s configuration. It is recommended to configure and activate the app’s audio session before preparing the engine. See https://developer.apple.com/library/archive/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/Introduction/Introduction.html for details.

Source

pub unsafe fn startAndReturnError(&self) -> Result<(), Retained<NSError>>

Start the engine.

Returns: YES for success

Calls prepare if it has not already been called since stop.

When the engine is rendering to/from an audio device, starts the audio hardware via the AVAudioInputNode and/or AVAudioOutputNode instances in the engine. Audio begins to flow through the engine. Reasons for potential failure to start in this mode include:

  1. There is problem in the structure of the graph. Input can’t be routed to output or to a recording tap through converter type nodes.
  2. An AVAudioSession error.
  3. The driver failed to start the hardware.

In manual rendering mode, prepares the engine to render when requested by the client.

On AVAudioSession supported platforms, this method may cause the audio session to be implicitly activated. It is recommended to configure and activate the app’s audio session before starting the engine. For more information, see the prepare method above.

Source

pub unsafe fn pause(&self)

Pause the engine.

When the engine is rendering to/from an audio device, stops the audio hardware and the flow of audio through the engine. When operating in this mode, it is recommended that the engine be paused or stopped (as applicable) when not in use, to minimize power consumption.

Pausing the engine does not deallocate the resources allocated by prepare. Resume the engine by invoking start again.

Source

pub unsafe fn reset(&self)

reset Reset all of the nodes in the engine.

This will reset all of the nodes in the engine. This is useful, for example, for silencing reverb and delay tails.

In manual rendering mode, the render timeline is reset to a sample time of zero.

Source

pub unsafe fn stop(&self)

When the engine is rendering to/from an audio device, stops the audio hardware and the engine. When operating in this mode, it is recommended that the engine be paused or stopped (as applicable) when not in use, to minimize power consumption.

Stopping the engine releases the resources allocated by prepare.

Source

pub unsafe fn inputConnectionPointForNode_inputBus( &self, node: &AVAudioNode, bus: AVAudioNodeBus, ) -> Option<Retained<AVAudioConnectionPoint>>

Available on crate features AVAudioConnectionPoint and AVAudioNode and AVAudioTypes only.

Get connection information on a node’s input bus.

Parameter node: The node whose input connection is being queried.

Parameter bus: The node’s input bus on which the connection is being queried.

Returns: An AVAudioConnectionPoint object with connection information on the node’s specified input bus.

Connections are always one-to-one or one-to-many, never many-to-one.

Returns nil if there is no connection on the node’s specified input bus.

Source

pub unsafe fn outputConnectionPointsForNode_outputBus( &self, node: &AVAudioNode, bus: AVAudioNodeBus, ) -> Retained<NSArray<AVAudioConnectionPoint>>

Available on crate features AVAudioConnectionPoint and AVAudioNode and AVAudioTypes only.

Get connection information on a node’s output bus.

Parameter node: The node whose output connections are being queried.

Parameter bus: The node’s output bus on which connections are being queried.

Returns: An array of AVAudioConnectionPoint objects with connection information on the node’s specified output bus.

Connections are always one-to-one or one-to-many, never many-to-one.

Returns an empty array if there are no connections on the node’s specified output bus.

Source

pub unsafe fn musicSequence(&self) -> MusicSequence

Available on crate feature objc2-audio-toolbox and non-watchOS only.

The MusicSequence previously attached to the engine (if any).

Source

pub unsafe fn setMusicSequence(&self, music_sequence: MusicSequence)

Available on crate feature objc2-audio-toolbox and non-watchOS only.

Setter for musicSequence.

§Safety

music_sequence must be a valid pointer or null.

Source

pub unsafe fn outputNode(&self) -> Retained<AVAudioOutputNode>

Available on crate features AVAudioIONode and AVAudioNode only.

The engine’s singleton output node.

Audio output is performed via an output node. The engine creates a singleton on demand when this property is first accessed. Connect another node to the input of the output node, or obtain a mixer that is connected there by default, using the “mainMixerNode” property.

When the engine is rendering to/from an audio device, the AVAudioSesssion category and/or availability of hardware determine whether an app can perform output. Check the output format of output node (i.e. hardware format) for non-zero sample rate and channel count to see if output is enabled. Trying to perform output through the output node when it is not enabled or available will cause the engine to throw an error (when possible) or an exception.

In manual rendering mode, the output format of the output node will determine the render format of the engine. It can be changed through enableManualRenderingMode:format:maximumFrameCount:error:.

Source

pub unsafe fn inputNode(&self) -> Retained<AVAudioInputNode>

Available on crate features AVAudioIONode and AVAudioNode only.

The engine’s singleton input node.

Audio input is performed via an input node. The engine creates a singleton on demand when this property is first accessed. To receive input, connect another node from the output of the input node, or create a recording tap on it.

When the engine is rendering to/from an audio device, the AVAudioSesssion category and/or availability of hardware determine whether an app can perform input. Check for the input node’s input format (i.e. hardware format) for non-zero sample rate and channel count to see if input is enabled. Trying to perform input through the input node when it is not enabled or available will cause the engine to throw an error (when possible) or an exception.

Note that if the engine has at any point previously had its inputNode enabled and permission to record was granted, then any time the engine is running, the mic-in-use indicator will appear.

For applications which may need to dynamically switch between output-only and input-output modes, it may be advantageous to use two engine instances.

In manual rendering mode, the input node can be used to synchronously supply data to the engine while it is rendering (see AVAudioInputNode(setManualRenderingInputPCMFormat:inputBlock:).

Source

pub unsafe fn mainMixerNode(&self) -> Retained<AVAudioMixerNode>

Available on crate features AVAudioMixerNode and AVAudioNode only.

The engine’s optional singleton main mixer node.

The engine will construct a singleton main mixer and connect it to the outputNode on demand, when this property is first accessed. You can then connect additional nodes to the mixer.

If the client has never explicitly set the connection format between the mainMixerNode and the outputNode, the engine will always set/update the format to track the format of the outputNode on (re)start, even after an AVAudioEngineConfigurationChangeNotification. Otherwise, it’s the client’s responsibility to set/update this connection format after an AVAudioEngineConfigurationChangeNotification.

By default, the mixer’s output format (sample rate and channel count) will track the format of the output node. You may however make the connection explicitly with a different format.

Source

pub unsafe fn isRunning(&self) -> bool

The engine’s running state.

Source

pub unsafe fn isAutoShutdownEnabled(&self) -> bool

When auto shutdown is enabled, the engine can start and stop the audio hardware dynamically, to conserve power. This is the enforced behavior on watchOS and can be optionally enabled on other platforms.

To conserve power, it is advised that the client pause/stop the engine when not in use. But when auto shutdown is enabled, the engine will stop the audio hardware if it was running idle for a certain duration, and restart it later when required. Note that, because this operation is dynamic, it may affect the start times of the source nodes (e.g. AVAudioPlayerNode), if the engine has to resume from its shutdown state.

On watchOS, auto shutdown is always enabled. On other platforms, it is disabled by default, but the client can enable it if needed.

This property is applicable only when the engine is rendering to/from an audio device. If the value is changed when the engine is in manual rendering mode, it will take effect whenever the engine is switched to render to/from the audio device.

Source

pub unsafe fn setAutoShutdownEnabled(&self, auto_shutdown_enabled: bool)

Source

pub unsafe fn attachedNodes(&self) -> Retained<NSSet<AVAudioNode>>

Available on crate feature AVAudioNode only.

Set of all nodes attached to the engine.

Source

pub unsafe fn enableManualRenderingMode_format_maximumFrameCount_error( &self, mode: AVAudioEngineManualRenderingMode, pcm_format: &AVAudioFormat, maximum_frame_count: AVAudioFrameCount, ) -> Result<(), Retained<NSError>>

Available on crate features AVAudioFormat and AVAudioTypes only.

Set the engine to operate in a manual rendering mode with the specified render format and maximum frame count.

Parameter mode: The manual rendering mode to use.

Parameter pcmFormat: The format of the output PCM audio data from the engine.

Parameter maximumFrameCount: The maximum number of PCM sample frames the engine will be asked to produce in any single render call.

Parameter outError: On exit, if the engine cannot switch to the manual rendering mode, a description of the error (see AVAudioEngineManualRenderingError for the possible errors).

Returns: YES for success.

Use this method to configure the engine to render in response to requests from the client.

The engine must be in a stopped state before calling this method. The render format must be a PCM format and match the format of the buffer to which the engine is asked to render (see renderOffline:toBuffer:error:).

It is advised to enable manual rendering mode soon after the engine is created, and before accessing any of mainMixerNode, inputNode or outputNode of the engine. Otherwise, accessing or interacting with the engine before enabling manual rendering mode could have the unintended side-effect of configuring the hardware for device-rendering mode.

The input data in manual rendering mode can be supplied through the source nodes, e.g. AVAudioPlayerNode, AVAudioInputNode etc.

When switching to manual rendering mode, the engine:

  1. Switches the input and output nodes to manual rendering mode. Their input and output formats may change.
  2. Removes any taps previously installed on the input and output nodes.
  3. Maintains all the engine connections as is.

Reasons for potential failure when switching to manual rendering mode include:

  • Engine is not in a stopped state.
Source

pub unsafe fn disableManualRenderingMode(&self)

Set the engine to render to/from an audio device.

When disabling the manual rendering mode, the engine:

  1. Stops and resets itself (see stop and reset).
  2. Switches the output/input nodes to render to/from an audio device. Their input and output formats may change.
  3. Removes any taps previously installed on the input and output nodes.
  4. Maintains all the engine connections as is.

Calling this method when the engine is already rendering to/from an audio device has no effect.

Source

pub unsafe fn manualRenderingBlock(&self) -> AVAudioEngineManualRenderingBlock

Available on crate features AVAudioTypes and block2 and objc2-core-audio-types only.

Block to render the engine operating in manual rendering mode

This block based render call must be used to render the engine when operating in AVAudioEngineManualRenderingModeRealtime. In this mode, the engine operates under realtime constraints and will not make any blocking call (e.g. calling libdispatch, blocking on a mutex, allocating memory etc.) while rendering.

Before invoking the rendering functionality, client must fetch this block and cache the result. The block can then be called from a realtime context, without any possibility of blocking.

When rendering in AVAudioEngineManualRenderingModeOffline, either this block based render call or renderOffline:toBuffer:error: ObjC method can be used. All the rules outlined in renderOffline:toBuffer:error: are applicable here as well.

§Safety
  • The returned block’s argument 2 must be a valid pointer.
  • The returned block’s argument 3 must be a valid pointer or null.
Source

pub unsafe fn isInManualRenderingMode(&self) -> bool

Whether or not the engine is operating in manual rendering mode, i.e. not connected to an audio device and rendering in response to the requests from the client

Source

pub unsafe fn manualRenderingMode(&self) -> AVAudioEngineManualRenderingMode

The manual rendering mode configured on the engine

This property is meaningful only when the engine is operating in manual rendering mode, i.e. when isInManualRenderingMode returns true.

Source

pub unsafe fn manualRenderingFormat(&self) -> Retained<AVAudioFormat>

Available on crate feature AVAudioFormat only.

The render format of the engine in manual rendering mode.

Querying this property when the engine is not in manual rendering mode will return an invalid format, with zero sample rate and channel count.

Source

pub unsafe fn manualRenderingMaximumFrameCount(&self) -> AVAudioFrameCount

Available on crate feature AVAudioTypes only.

The maximum number of PCM sample frames the engine can produce in any single render call in the manual rendering mode.

Querying this property when the engine is not in manual rendering mode will return zero.

Source

pub unsafe fn manualRenderingSampleTime(&self) -> AVAudioFramePosition

Available on crate feature AVAudioTypes only.

Indicates where the engine is on its render timeline in manual rendering mode.

The timeline in manual rendering mode starts at a sample time of zero, and is in terms of the render format’s sample rate. Resetting the engine (see reset) will reset the timeline back to zero.

Source

pub unsafe fn connectMIDI_to_format_block( &self, source_node: &AVAudioNode, destination_node: &AVAudioNode, format: Option<&AVAudioFormat>, tap_block: AUMIDIOutputEventBlock, )

👎Deprecated
Available on crate feature AVAudioFormat and crate feature AVAudioNode and crate feature objc2-audio-toolbox and non-watchOS only.

Establish a MIDI only connection between two nodes.

Parameter sourceNode: The source node.

Parameter destinationNode: The destination node.

Parameter format: If non-nil, the format of the source node’s output bus is set to this format. In all cases, the format of the source nodes’ output bus has to match with the destination nodes’ output bus format. Although the output bus of the source is not in use, the format needs to be set in order to be able to use the sample rate for MIDI event timing calculations.

Parameter tapBlock: If non-nil, this block is called from the source node’s AUMIDIOutputEventBlock on the realtime thread. The host can tap the MIDI data of the source node through this block. May be nil.

Use this method to establish a MIDI only connection between a source node and a destination node that has MIDI input capability.

The source node can only be a AVAudioUnit node of type kAudioUnitType_MIDIProcessor. The destination node types can be kAudioUnitType_MusicDevice, kAudioUnitType_MusicEffect or kAudioUnitType_MIDIProcessor.

Note that any pre-existing MIDI connection involving the destination will be broken.

Any client installed block on the source node’s audio unit AUMIDIOutputEventBlock will be overwritten when making the MIDI connection.

§Safety

tap_block must be a valid pointer or null.

Source

pub unsafe fn connectMIDI_toNodes_format_block( &self, source_node: &AVAudioNode, destination_nodes: &NSArray<AVAudioNode>, format: Option<&AVAudioFormat>, tap_block: AUMIDIOutputEventBlock, )

👎Deprecated
Available on crate feature AVAudioFormat and crate feature AVAudioNode and crate feature objc2-audio-toolbox and non-watchOS only.

Establish a MIDI only connection between a source node and multiple destination nodes.

Parameter sourceNode: The source node.

Parameter destinationNodes: An array of AVAudioNodes specifying destination nodes.

Parameter format: If non-nil, the format of the source node’s output bus is set to this format. In all cases, the format of the source nodes’ output bus has to match with the destination nodes’ output bus format. Although the output bus of the source is not in use, the format needs to be set in order to be able to use the sample rate for MIDI event timing calculations.

Parameter tapBlock: If non-nil, this block is called from the source node’s AUMIDIOutputEventBlock on the realtime thread. The host can tap the MIDI data of the source node through this block. May be nil.

Use this method to establish a MIDI only connection between a source node and multiple destination nodes.

The source node can only be a AVAudioUnit node of type kAudioUnitType_MIDIProcessor. The destination node types can be kAudioUnitType_MusicDevice, kAudioUnitType_MusicEffect or kAudioUnitType_MIDIProcessor.

MIDI connections made using this method are either one-to-one (when a single destination connection is specified) or one-to-many (when multiple connections are specified), but never many-to-one.

Note that any pre-existing connection involving the destination will be broken.

Any client installed block on the source node’s audio unit AUMIDIOutputEventBlock will be overwritten when making the MIDI connection.

§Safety

tap_block must be a valid pointer or null.

Source

pub unsafe fn disconnectMIDI_from( &self, source_node: &AVAudioNode, destination_node: &AVAudioNode, )

Available on crate feature AVAudioNode only.

Remove a MIDI connection between two nodes.

Parameter sourceNode: The node whose MIDI output is to be disconnected.

Parameter destinationNode: The node whose MIDI input is to be disconnected.

If a tap block is installed on the source node, it will be removed when the last connection from the source node is removed.

Source

pub unsafe fn disconnectMIDI_fromNodes( &self, source_node: &AVAudioNode, destination_nodes: &NSArray<AVAudioNode>, )

Available on crate feature AVAudioNode only.

Remove a MIDI connection between one source node and multiple destination nodes.

Parameter sourceNode: The node whose MIDI output is to be disconnected.

Parameter destinationNodes: An array of AVAudioNodes specifying nodes whose MIDI input is to be disconnected.

If a tap block is installed on the source node, it will be removed when the last connection from the source node is removed.

Source

pub unsafe fn disconnectMIDIInput(&self, node: &AVAudioNode)

Available on crate feature AVAudioNode only.

Disconnects all input MIDI connections of this node.

Parameter node: The node whose MIDI input is to be disconnected.

Source

pub unsafe fn disconnectMIDIOutput(&self, node: &AVAudioNode)

Available on crate feature AVAudioNode only.

Disconnects all output MIDI connections of this node.

Parameter node: The node whose MIDI outputs are to be disconnected.

Source§

impl AVAudioEngine

Methods declared on superclass NSObject.

Source

pub unsafe fn new() -> Retained<Self>

Methods from Deref<Target = NSObject>§

Source

pub fn doesNotRecognizeSelector(&self, sel: Sel) -> !

Handle messages the object doesn’t recognize.

See Apple’s documentation for details.

Methods from Deref<Target = AnyObject>§

Source

pub fn class(&self) -> &'static AnyClass

Dynamically find the class of this object.

§Panics

May panic if the object is invalid (which may be the case for objects returned from unavailable init/new methods).

§Example

Check that an instance of NSObject has the precise class NSObject.

use objc2::ClassType;
use objc2::runtime::NSObject;

let obj = NSObject::new();
assert_eq!(obj.class(), NSObject::class());
Source

pub unsafe fn get_ivar<T>(&self, name: &str) -> &T
where T: Encode,

👎Deprecated: this is difficult to use correctly, use Ivar::load instead.

Use Ivar::load instead.

§Safety

The object must have an instance variable with the given name, and it must be of type T.

See Ivar::load_ptr for details surrounding this.

Source

pub fn downcast_ref<T>(&self) -> Option<&T>
where T: DowncastTarget,

Attempt to downcast the object to a class of type T.

This is the reference-variant. Use Retained::downcast if you want to convert a retained object to another type.

§Mutable classes

Some classes have immutable and mutable variants, such as NSString and NSMutableString.

When some Objective-C API signature says it gives you an immutable class, it generally expects you to not mutate that, even though it may technically be mutable “under the hood”.

So using this method to convert a NSString to a NSMutableString, while not unsound, is generally frowned upon unless you created the string yourself, or the API explicitly documents the string to be mutable.

See Apple’s documentation on mutability and on isKindOfClass: for more details.

§Generic classes

Objective-C generics are called “lightweight generics”, and that’s because they aren’t exposed in the runtime. This makes it impossible to safely downcast to generic collections, so this is disallowed by this method.

You can, however, safely downcast to generic collections where all the type-parameters are AnyObject.

§Panics

This works internally by calling isKindOfClass:. That means that the object must have the instance method of that name, and an exception will be thrown (if CoreFoundation is linked) or the process will abort if that is not the case. In the vast majority of cases, you don’t need to worry about this, since both root objects NSObject and NSProxy implement this method.

§Examples

Cast an NSString back and forth from NSObject.

use objc2::rc::Retained;
use objc2_foundation::{NSObject, NSString};

let obj: Retained<NSObject> = NSString::new().into_super();
let string = obj.downcast_ref::<NSString>().unwrap();
// Or with `downcast`, if we do not need the object afterwards
let string = obj.downcast::<NSString>().unwrap();

Try (and fail) to cast an NSObject to an NSString.

use objc2_foundation::{NSObject, NSString};

let obj = NSObject::new();
assert!(obj.downcast_ref::<NSString>().is_none());

Try to cast to an array of strings.

use objc2_foundation::{NSArray, NSObject, NSString};

let arr = NSArray::from_retained_slice(&[NSObject::new()]);
// This is invalid and doesn't type check.
let arr = arr.downcast_ref::<NSArray<NSString>>();

This fails to compile, since it would require enumerating over the array to ensure that each element is of the desired type, which is a performance pitfall.

Downcast when processing each element instead.

use objc2_foundation::{NSArray, NSObject, NSString};

let arr = NSArray::from_retained_slice(&[NSObject::new()]);

for elem in arr {
    if let Some(data) = elem.downcast_ref::<NSString>() {
        // handle `data`
    }
}

Trait Implementations§

Source§

impl AsRef<AVAudioEngine> for AVAudioEngine

Source§

fn as_ref(&self) -> &Self

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl AsRef<AnyObject> for AVAudioEngine

Source§

fn as_ref(&self) -> &AnyObject

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl AsRef<NSObject> for AVAudioEngine

Source§

fn as_ref(&self) -> &NSObject

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Borrow<AnyObject> for AVAudioEngine

Source§

fn borrow(&self) -> &AnyObject

Immutably borrows from an owned value. Read more
Source§

impl Borrow<NSObject> for AVAudioEngine

Source§

fn borrow(&self) -> &NSObject

Immutably borrows from an owned value. Read more
Source§

impl ClassType for AVAudioEngine

Source§

const NAME: &'static str = "AVAudioEngine"

The name of the Objective-C class that this type represents. Read more
Source§

type Super = NSObject

The superclass of this class. Read more
Source§

type ThreadKind = <<AVAudioEngine as ClassType>::Super as ClassType>::ThreadKind

Whether the type can be used from any thread, or from only the main thread. Read more
Source§

fn class() -> &'static AnyClass

Get a reference to the Objective-C class that this type represents. Read more
Source§

fn as_super(&self) -> &Self::Super

Get an immutable reference to the superclass.
Source§

impl Debug for AVAudioEngine

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for AVAudioEngine

Source§

type Target = NSObject

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl Hash for AVAudioEngine

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Message for AVAudioEngine

Source§

fn retain(&self) -> Retained<Self>
where Self: Sized,

Increment the reference count of the receiver. Read more
Source§

impl NSObjectProtocol for AVAudioEngine

Source§

fn isEqual(&self, other: Option<&AnyObject>) -> bool
where Self: Sized + Message,

Check whether the object is equal to an arbitrary other object. Read more
Source§

fn hash(&self) -> usize
where Self: Sized + Message,

An integer that can be used as a table address in a hash table structure. Read more
Source§

fn isKindOfClass(&self, cls: &AnyClass) -> bool
where Self: Sized + Message,

Check if the object is an instance of the class, or one of its subclasses. Read more
Source§

fn is_kind_of<T>(&self) -> bool
where T: ClassType, Self: Sized + Message,

👎Deprecated: use isKindOfClass directly, or cast your objects with AnyObject::downcast_ref
Check if the object is an instance of the class type, or one of its subclasses. Read more
Source§

fn isMemberOfClass(&self, cls: &AnyClass) -> bool
where Self: Sized + Message,

Check if the object is an instance of a specific class, without checking subclasses. Read more
Source§

fn respondsToSelector(&self, aSelector: Sel) -> bool
where Self: Sized + Message,

Check whether the object implements or inherits a method with the given selector. Read more
Source§

fn conformsToProtocol(&self, aProtocol: &AnyProtocol) -> bool
where Self: Sized + Message,

Check whether the object conforms to a given protocol. Read more
Source§

fn description(&self) -> Retained<NSObject>
where Self: Sized + Message,

A textual representation of the object. Read more
Source§

fn debugDescription(&self) -> Retained<NSObject>
where Self: Sized + Message,

A textual representation of the object to use when debugging. Read more
Source§

fn isProxy(&self) -> bool
where Self: Sized + Message,

Check whether the receiver is a subclass of the NSProxy root class instead of the usual NSObject. Read more
Source§

fn retainCount(&self) -> usize
where Self: Sized + Message,

The reference count of the object. Read more
Source§

impl PartialEq for AVAudioEngine

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl RefEncode for AVAudioEngine

Source§

const ENCODING_REF: Encoding = <NSObject as ::objc2::RefEncode>::ENCODING_REF

The Objective-C type-encoding for a reference of this type. Read more
Source§

impl DowncastTarget for AVAudioEngine

Source§

impl Eq for AVAudioEngine

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T> AnyThread for T
where T: ClassType<ThreadKind = dyn AnyThread + 'a> + ?Sized,

Source§

fn alloc() -> Allocated<Self>
where Self: Sized + ClassType,

Allocate a new instance of the class. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> AutoreleaseSafe for T
where T: ?Sized,