AVAssetWriter

Struct AVAssetWriter 

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

AVAssetWriter provides services for writing media data to a new file,

Instances of AVAssetWriter can write media to new files in formats such as the QuickTime movie file format or the MPEG-4 file format. AVAssetWriter has support for automatic interleaving of media data for multiple concurrent tracks. Source media data can be obtained from instances of AVAssetReader for one or more assets or from other sources outside of AVFoundation.

Instances of AVAssetWriter can re-encode media samples as they are written. Instances of AVAssetWriter can also optionally write metadata collections to the output file.

A single instance of AVAssetWriter can be used once to write to a single file. Clients that wish to write to files multiple times must use a new instance of AVAssetWriter each time.

See also Apple’s documentation

Implementations§

Source§

impl AVAssetWriter

Source

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

Source

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

Source

pub unsafe fn assetWriterWithURL_fileType_error( output_url: &NSURL, output_file_type: &AVFileType, ) -> Result<Retained<Self>, Retained<NSError>>

Available on crate feature AVMediaFormat only.

Returns an instance of AVAssetWriter configured to write to a file in a specified container format.

Parameter URL: The location of the file to be written. The URL must be a file URL.

Parameter fileType: A UTI indicating the format of the file to be written.

Parameter outError: On return, if initialization of the AVAssetWriter fails, points to an NSError describing the nature of the failure.

Returns: An instance of AVAssetWriter.

Writing will fail if a file already exists at the specified URL.

UTIs for container formats that can be written are declared in AVMediaFormat.h.

Source

pub unsafe fn initWithURL_fileType_error( this: Allocated<Self>, output_url: &NSURL, output_file_type: &AVFileType, ) -> Result<Retained<Self>, Retained<NSError>>

Available on crate feature AVMediaFormat only.

Creates an instance of AVAssetWriter configured to write to a file in a specified container format.

Parameter URL: The location of the file to be written. The URL must be a file URL.

Parameter fileType: A UTI indicating the format of the file to be written.

Parameter outError: On return, if initialization of the AVAssetWriter fails, points to an NSError describing the nature of the failure.

Returns: An instance of AVAssetWriter.

Writing will fail if a file already exists at the specified URL.

This method throws an exception if the output file type is not declared in AVMediaFormat.h.

Source

pub unsafe fn initWithContentType( this: Allocated<Self>, output_content_type: &UTType, ) -> Retained<Self>

Available on crate feature objc2-uniform-type-identifiers only.

Creates an instance of AVAssetWriter configured to output segment data in a specified container format.

Parameter outputContentType: A UTType indicating the format of the segment data to be output.

Returns: An instance of AVAssetWriter.

Clients that want to receive segment data through the -assetWriter:didOutputSegmentData:segmentType:segmentReport: or -assetWriter:didOutputSegmentData:segmentType: delegate method should use this initializer instead of -initWithURL:fileType:error:.

Clients may use +typeWithIdentifier: with a UTI to create an instance of UTType. See <UniformTypeIdentifiers /UTType.h>.

This method throws an exception if the output content type UTI for container format is not declared in AVMediaFormat.h.

Source

pub unsafe fn outputURL(&self) -> Retained<NSURL>

The location of the file for which the instance of AVAssetWriter was initialized for writing.

You may use [[UTType typeWithIdentifier:outputFileType] preferredFilenameExtension] to obtain an appropriate path extension for the outputFileType you have specified. For more information, see <UniformTypeIdentifiers /UTType.h>.

Source

pub unsafe fn outputFileType(&self) -> Retained<AVFileType>

Available on crate feature AVMediaFormat only.

The UTI of the file format of the file for which the instance of AVAssetWriter was initialized for writing.

Source

pub unsafe fn availableMediaTypes(&self) -> Retained<NSArray<AVMediaType>>

Available on crate feature AVMediaFormat only.

The media types for which inputs can be added to the receiver.

Some media types may not be accepted within the file format with which an AVAssetWriter was initialized.

Source

pub unsafe fn status(&self) -> AVAssetWriterStatus

The status of writing samples to the receiver’s output file.

The value of this property is an AVAssetWriterStatus that indicates whether writing is in progress, has completed successfully, has been canceled, or has failed. Clients of AVAssetWriterInput objects should check the value of this property after appending samples fails to determine why no more samples could be written. This property is thread safe.

Source

pub unsafe fn error(&self) -> Option<Retained<NSError>>

If the receiver’s status is AVAssetWriterStatusFailed, this describes the error that caused the failure.

The value of this property is an NSError that describes what caused the receiver to no longer be able to write to its output file. If the receiver’s status is not AVAssetWriterStatusFailed, the value of this property is nil. This property is thread safe.

Source

pub unsafe fn metadata(&self) -> Retained<NSArray<AVMetadataItem>>

Available on crate feature AVMetadataItem only.

A collection of metadata to be written to the receiver’s output file.

The value of this property is an array of AVMetadataItem objects representing the collection of top-level metadata to be written in the output file.

This property cannot be set after writing has started.

Source

pub unsafe fn setMetadata(&self, metadata: &NSArray<AVMetadataItem>)

Available on crate feature AVMetadataItem only.

Setter for metadata.

This is copied when set.

Source

pub unsafe fn shouldOptimizeForNetworkUse(&self) -> bool

Specifies whether the output file should be written in way that makes it more suitable for playback over a network

When the value of this property is YES, the output file will be written in such a way that playback can start after only a small amount of the file is downloaded.

This property cannot be set after writing has started.

Source

pub unsafe fn setShouldOptimizeForNetworkUse( &self, should_optimize_for_network_use: bool, )

Source

pub unsafe fn directoryForTemporaryFiles(&self) -> Option<Retained<NSURL>>

Specifies a directory that is suitable for containing temporary files generated during the process of writing an asset.

AVAssetWriter may need to write temporary files when configured in certain ways, such as when performsMultiPassEncodingIfSupported is set to YES on one or more of its inputs. This property can be used to control where in the filesystem those temporary files are created. All temporary files will be deleted when asset writing is completed, is canceled, or fails.

When the value of this property is nil, the asset writer will choose a suitable location when writing temporary files. The default value is nil.

This property cannot be set after writing has started. The asset writer will fail if a file cannot be created in this directory (for example, due to insufficient permissions).

Source

pub unsafe fn setDirectoryForTemporaryFiles( &self, directory_for_temporary_files: Option<&NSURL>, )

Setter for directoryForTemporaryFiles.

This is copied when set.

Source

pub unsafe fn inputs(&self) -> Retained<NSArray<AVAssetWriterInput>>

Available on crate feature AVAssetWriterInput only.

The inputs from which the asset writer receives media data.

The value of this property is an NSArray containing concrete instances of AVAssetWriterInput. Inputs can be added to the receiver using the addInput: method.

Source

pub unsafe fn canApplyOutputSettings_forMediaType( &self, output_settings: Option<&NSDictionary<NSString, AnyObject>>, media_type: &AVMediaType, ) -> bool

Available on crate feature AVMediaFormat only.

Tests whether output settings for a specific media type are supported by the receiver’s file format.

Parameter outputSettings: The output settings that are to be tested.

Parameter mediaType: The media type for which the output settings are to be tested. Media types are defined in AVMediaFormat.h.

Returns: A BOOL indicating whether the given output settings can be used for the given media type.

This method determines whether the output settings for the specified media type can be used with the receiver’s file format. For example, video compression settings that specify H.264 compression are not compatible with file formats that cannot contain H.264-compressed video.

Attempting to add an input with output settings and a media type for which this method returns NO will cause an exception to be thrown.

§Safety

output_settings generic should be of the correct type.

Source

pub unsafe fn canAddInput(&self, input: &AVAssetWriterInput) -> bool

Available on crate feature AVAssetWriterInput only.

Tests whether an input can be added to the receiver.

Parameter input: The AVAssetWriterInput object to be tested.

Returns: A BOOL indicating whether the input can be added to the receiver.

An input that accepts media data of a type that is not compatible with the receiver, or with output settings that are not compatible with the receiver, cannot be added.

Source

pub unsafe fn addInput(&self, input: &AVAssetWriterInput)

Available on crate feature AVAssetWriterInput only.

Adds an input to the receiver.

Parameter input: The AVAssetWriterInput object to be added.

Inputs are created with a media type and output settings. These both must be compatible with the receiver.

Inputs cannot be added after writing has started.

This method throws an exception if any of the following conditions are satisfied:

  • the input’s media type is not allowed for this asset writer
  • writing uncompressed video in a specific format
  • passthrough* to files (other than AVFileTypeQuickTimeMovie) is missing a format hint in the AVAssetWriterInput initializer
  • passthrough* is not supported for this media/file type combination (for example, AVFileTypeWAVE only supports AVMediaTypeAudio)

Passthrough is indicated when the input’s output settings are nil.

Source

pub unsafe fn startWriting(&self) -> bool

Prepares the receiver for accepting input and for writing its output to its output file.

Returns: A BOOL indicating whether writing successfully started.

This method must be called after all inputs have been added and other configuration properties have been set in order to tell the receiver to prepare for writing. After this method is called, clients can start writing sessions using startSessionAtSourceTime: and can write media samples using the methods provided by each of the receiver’s inputs.

If writing cannot be started, this method returns NO. Clients can check the values of the status and error properties for more information on why writing could not be started.

On iOS, if the status of an AVAssetWriter is AVAssetWriterStatusWriting when the client app goes into the background, its status will change to AVAssetWriterStatusFailed and appending to any of its inputs will fail. You may want to use -[UIApplication beginBackgroundTaskWithExpirationHandler:] to avoid being interrupted in the middle of a writing session and to finish writing the data that has already been appended. For more information about executing code in the background, see the iOS Application Programming Guide.

Source

pub unsafe fn startSessionAtSourceTime(&self, start_time: CMTime)

Available on crate feature objc2-core-media only.

Initiates a sample-writing session for the receiver.

Parameter startTime: The starting asset time for the sample-writing session, in the timeline of the source samples.

Sequences of sample data appended to the asset writer inputs are considered to fall within “sample-writing sessions”, initiated with this method. Accordingly, this method must be called after writing has started (using -startWriting) but before any sample data is appended to the receiver’s inputs.

Each writing session has a start time which, where allowed by the file format being written, defines the mapping from the timeline of source samples to the timeline of the written file. In the case of the QuickTime movie file format, the first session begins at movie time 0, so a sample appended with timestamp T will be played at movie time (T-startTime). Samples with timestamps earlier than startTime will still be added to the output file but will be edited out (i.e. not presented during playback). If the earliest appended sample for an input has a timestamp later than than startTime, an empty edit will be inserted to preserve synchronization between tracks of the output asset.

To end the session started by use of this method, use -endSessionAtSourceTime: or -finishWritingWithCompletionHandler:. It is an error to invoke -startSessionAtSourceTime: twice in a row without invoking -endSessionAtSourceTime: in between.

NOTE: Multiple sample-writing sessions are currently not supported. It is an error to call -startSessionAtSourceTime: a second time after calling -endSessionAtSourceTime:.

Source

pub unsafe fn endSessionAtSourceTime(&self, end_time: CMTime)

Available on crate feature objc2-core-media only.

Concludes a sample-writing session.

Parameter endTime: The ending asset time for the sample-writing session, in the timeline of the source samples.

Call this method to complete a session started with -startSessionAtSourceTime:.

The endTime defines the moment on the timeline of source samples at which the session ends. In the case of the QuickTime movie file format, each sample-writing session’s startTime…endTime pair corresponds to a period of movie time into which the session’s samples are inserted. Samples with timestamps that are later than the session end time will still be added to the written file but will be edited out (i.e. not presented during playback). So if the first session has duration D1 = endTime - startTime, it will be inserted into the written file at time 0 through D1; the second session would be inserted into the written file at time D1 through D1+D2, etc. It is legal to have a session with no samples; this will cause creation of an empty edit of the prescribed duration.

It is not mandatory to call -endSessionAtSourceTime:; if -finishWritingWithCompletionHandler: is called without first invoking -endSessionAtSourceTime:, the session’s effective end time will be the latest end timestamp of the session’s appended samples (i.e. no samples will be edited out at the end).

It is an error to append samples outside of a sample-writing session. To append more samples after invoking -endSessionAtSourceTime:, you must first start a new session using -startSessionAtSourceTime:.

NOTE: Multiple sample-writing sessions are currently not supported. It is an error to call -startSessionAtSourceTime: a second time after calling -endSessionAtSourceTime:.

This method throws an exception if the session is ended without first starting it.

Source

pub unsafe fn cancelWriting(&self)

Cancels the creation of the output file.

If the status of the receiver is “failed” or “completed,” -cancelWriting is a no-op. Otherwise, this method will block until writing is canceled.

If an output file was created by the receiver during the writing process, -cancelWriting will delete the file.

This method should not be called concurrently with -[AVAssetWriterInput appendSampleBuffer:] or -[AVAssetWriterInputPixelBufferAdaptor appendPixelBuffer:withPresentationTime:].

Source

pub unsafe fn finishWriting(&self) -> bool

👎Deprecated

Completes the writing of the output file.

Returns: A BOOL indicating whether writing successfully finished.

This method is deprecated. Use finishWritingWithCompletionHandler: instead.

This method will block until writing is finished. When this method returns successfully, the file being written by the receiver is complete and ready to use.

Because this method is blocking and can take a long time to execute (especially with shouldOptimizeForNetworkUse set to YES), it should not be called from the main thread. Doing so can cause the finishWriting operation to fail.

If writing cannot be finished, this method returns NO. Clients can check the values of the status and error properties for more information on why writing could not be finished.

This method should not be called concurrently with -[AVAssetWriterInput appendSampleBuffer:] or -[AVAssetWriterInputPixelBufferAdaptor appendPixelBuffer:withPresentationTime:].

Source

pub unsafe fn finishWritingWithCompletionHandler( &self, handler: &DynBlock<dyn Fn()>, )

Available on crate feature block2 only.

Marks all unfinished inputs as finished and completes the writing of the output file.

This method returns immediately and causes its work to be performed asynchronously.

When the writing of the output file is finished, or if a failure or a cancellation occurs in the meantime, the specified handler will be invoked to indicate completion of the operation. To determine whether the operation succeeded, your handler can check the value of AVAssetWriter.status. If the status is AVAssetWriterStatusFailed, AVAsset.error will contain an instance of NSError that describes the failure.

To guarantee that all sample buffers are successfully written, ensure all calls to -[AVAssetWriterInput appendSampleBuffer:] or -[AVAssetWriterInputPixelBufferAdaptor appendPixelBuffer:withPresentationTime:] have returned before invoking this method.

§Safety

handler block must be sendable.

Source§

impl AVAssetWriter

AVAssetWriterFileTypeSpecificProperties.

Source

pub unsafe fn movieFragmentInterval(&self) -> CMTime

Available on crate feature objc2-core-media only.

For file types that support movie fragments, specifies the frequency at which movie fragments should be written.

When movie fragments are used, a partially written asset whose writing is unexpectedly interrupted can be successfully opened and played up to multiples of the specified time interval. The default value of this property is kCMTimeInvalid, which indicates that movie fragments should not be used.

When using movie fragments, for best writing performance to external storage devices, set the movieFragmentInterval to 10 seconds or greater.

This property cannot be set after writing has started.

Source

pub unsafe fn setMovieFragmentInterval(&self, movie_fragment_interval: CMTime)

Available on crate feature objc2-core-media only.
Source

pub unsafe fn initialMovieFragmentInterval(&self) -> CMTime

Available on crate feature objc2-core-media only.

For file types that support movie fragments, specifies the interval at which initial movie fragment should be written.

This property is irrelevant if the movieFragmentInterval property is not set. The default value is kCMTimeInvalid, which indicates that the interval for initial movie fragment is same as the one specified by movieFragmentInterval property.

This property cannot be set after writing has started.

Source

pub unsafe fn setInitialMovieFragmentInterval( &self, initial_movie_fragment_interval: CMTime, )

Available on crate feature objc2-core-media only.
Source

pub unsafe fn initialMovieFragmentSequenceNumber(&self) -> NSInteger

For file types that support movie fragments, specifies the initial movie fragment sequence number.

The value must be equal to or greater than 1.

The default value is 1.

Note that if you combine movie fragments produced by an instance of AVAssetWriter with additional movie fragments, produced either by a different instance of AVAssetWriter or by some other means, it is necessary to ensure that movie fragment sequence numbers increase monotonically across the entire combined collection, in temporal order.

This property cannot be set after writing has started.

Source

pub unsafe fn setInitialMovieFragmentSequenceNumber( &self, initial_movie_fragment_sequence_number: NSInteger, )

Source

pub unsafe fn producesCombinableFragments(&self) -> bool

For file types that support fragmented MPEG-4, specifies whether the movie fragments should be produced in way that makes them suitable for combining with movie fragments produced by one or more other instances of AVAssetWriter into a single fragment stream of uniform encoding.

The default value is NO.

When multiple instances of AVAssetWriter are used to produce distinct streams that complement each other, for example to create HLS encoding or bitrate variants, it’s not necessary to set this property to YES.

This property cannot be set after writing has started.

Source

pub unsafe fn setProducesCombinableFragments( &self, produces_combinable_fragments: bool, )

Source

pub unsafe fn overallDurationHint(&self) -> CMTime

Available on crate feature objc2-core-media only.

For file types that support movie fragments, provides a hint of the final duration of the file to be written

The value of this property must be a nonnegative, numeric CMTime. Alternatively, if the value of this property is an invalid CMTime (e.g. kCMTimeInvalid), no overall duration hint will be written to the file. The default value is kCMTimeInvalid.

This property is currently ignored if movie fragments are not being written. Use the movieFragmentInterval property to enable movie fragments.

This property cannot be set after writing has started.

Source

pub unsafe fn setOverallDurationHint(&self, overall_duration_hint: CMTime)

Available on crate feature objc2-core-media only.

Setter for overallDurationHint.

Source

pub unsafe fn movieTimeScale(&self) -> CMTimeScale

Available on crate feature objc2-core-media only.

For file types that contain a ‘moov’ atom, such as QuickTime Movie files, specifies the asset-level time scale to be used.

The default value is 0, which indicates that the receiver should choose a convenient value, if applicable.

This property cannot be set after writing has started.

Source

pub unsafe fn setMovieTimeScale(&self, movie_time_scale: CMTimeScale)

Available on crate feature objc2-core-media only.

Setter for movieTimeScale.

Source§

impl AVAssetWriter

AVAssetWriterInputGroups.

Source

pub unsafe fn canAddInputGroup( &self, input_group: &AVAssetWriterInputGroup, ) -> bool

Available on crate feature AVMediaSelectionGroup only.

Tests whether an input group can be added to the receiver.

Parameter inputGroup: The AVAssetWriterInputGroup object to be tested.

Returns: A BOOL indicating whether the input group can be added to the receiver.

If outputFileType specifies a container format that does not support mutually exclusive relationships among tracks, or if the specified instance of AVAssetWriterInputGroup contains inputs with media types that cannot be related, the group cannot be added to the AVAssetWriter.

This method throws an exception if any of the following conditions are satisfied:

  • this writer’s output file type does not support mutually exclusive relationships among tracks (allowed types are AVFileTypeQuickTimeMovie, AVFileTypeAppleM4A, AVFileTypeAppleM4V, AVFileType3GPP, AVFileTypeMPEG4)
  • any AVAssetWriterInput in the input group is also present in an input group already added
Source

pub unsafe fn addInputGroup(&self, input_group: &AVAssetWriterInputGroup)

Available on crate feature AVMediaSelectionGroup only.
Source

pub unsafe fn inputGroups(&self) -> Retained<NSArray<AVAssetWriterInputGroup>>

Available on crate feature AVMediaSelectionGroup only.

The instances of AVAssetWriterInputGroup that have been added to the AVAssetWriter.

The value of this property is an NSArray containing concrete instances of AVAssetWriterInputGroup. Input groups can be added to the receiver using the addInputGroup: method.

Source§

impl AVAssetWriter

AVAssetWriterSegmentation.

Source

pub unsafe fn preferredOutputSegmentInterval(&self) -> CMTime

Available on crate feature objc2-core-media only.

Specifies preferred segment interval.

The default value is kCMTimeInvalid, which means that the receiver will choose an appropriate default value. The value can be set to positive numeric or kCMTimeIndefinite. If the value is kCMTimeIndefinite, every time a client calls -flushSegment the receiver outputs a segment data.

This property cannot be set after writing has started.

Source

pub unsafe fn setPreferredOutputSegmentInterval( &self, preferred_output_segment_interval: CMTime, )

Available on crate feature objc2-core-media only.
Source

pub unsafe fn initialSegmentStartTime(&self) -> CMTime

Available on crate feature objc2-core-media only.

Specifies start time of initial segment.

A numeric time must be set if the value of preferredOutputSegmentInterval property is positive numeric. If not, this property is irrelevant.

This property cannot be set after writing has started.

Source

pub unsafe fn setInitialSegmentStartTime( &self, initial_segment_start_time: CMTime, )

Available on crate feature objc2-core-media only.
Source

pub unsafe fn outputFileTypeProfile( &self, ) -> Option<Retained<AVFileTypeProfile>>

Available on crate feature AVMediaFormat only.

Specifies a file type profile for the specified file type.

The default value is nil, which means that the receiver will choose an appropriate default profile based on the specified file type.

Clients that want to receive segment data that is suitable for streaming through the -assetWriter:didOutputSegmentData:segmentType:segmentReport: or -assetWriter:didOutputSegmentData:segmentType: delegate method should set AVFileTypeProfileMPEG4AppleHLS, or AVFileTypeProfileMPEG4CMAFCompliant to require output that is specifically compliant with CMAF format, with AVFileTypeMPEG4 file type.

File type profiles are declared in AVMediaFormat.h.

This property cannot be set after writing has started.

Source

pub unsafe fn setOutputFileTypeProfile( &self, output_file_type_profile: Option<&AVFileTypeProfile>, )

Available on crate feature AVMediaFormat only.

Setter for outputFileTypeProfile.

This is copied when set.

Source

pub unsafe fn delegate( &self, ) -> Option<Retained<ProtocolObject<dyn AVAssetWriterDelegate>>>

An object that implements one or more of the methods in the AVAssetWriterDelegate protocol.

This property cannot be set after writing has started.

Source

pub unsafe fn setDelegate( &self, delegate: Option<&ProtocolObject<dyn AVAssetWriterDelegate>>, )

Setter for delegate.

This is a weak property.

Source

pub unsafe fn flushSegment(&self)

Closes the current segment and outputs it to the -assetWriter:didOutputSegmentData:segmentType:segmentReport: or -assetWriter:didOutputSegmentData:segmentType: delegate method.

This method throws an exception if the delegate method to output segment data is not implemented, or if the value of the preferredOutputSegmentInterval property is not kCMTimeIndefinite.

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<AVAssetWriter> for AVAssetWriter

Source§

fn as_ref(&self) -> &Self

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

impl AsRef<AnyObject> for AVAssetWriter

Source§

fn as_ref(&self) -> &AnyObject

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

impl AsRef<NSObject> for AVAssetWriter

Source§

fn as_ref(&self) -> &NSObject

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

impl Borrow<AnyObject> for AVAssetWriter

Source§

fn borrow(&self) -> &AnyObject

Immutably borrows from an owned value. Read more
Source§

impl Borrow<NSObject> for AVAssetWriter

Source§

fn borrow(&self) -> &NSObject

Immutably borrows from an owned value. Read more
Source§

impl ClassType for AVAssetWriter

Source§

const NAME: &'static str = "AVAssetWriter"

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 = <<AVAssetWriter 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 AVAssetWriter

Source§

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

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

impl Deref for AVAssetWriter

Source§

type Target = NSObject

The resulting type after dereferencing.
Source§

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

Dereferences the value.
Source§

impl Hash for AVAssetWriter

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 AVAssetWriter

Source§

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

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

impl NSObjectProtocol for AVAssetWriter

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 AVAssetWriter

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 AVAssetWriter

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 AVAssetWriter

Source§

impl Eq for AVAssetWriter

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,