Struct objc2::rc::Id

source · []
#[repr(transparent)]
pub struct Id<T: ?Sized, O: Ownership> { /* private fields */ }
Expand description

An pointer for Objective-C reference counted objects.

Id strongly references or “retains” the given object T, and “releases” it again when dropped, thereby ensuring it will be deallocated at the right time.

An Id can either be Owned or Shared, represented with the O type parameter.

If owned, it is guaranteed that there are no other references to the object, and the Id can therefore be mutably dereferenced.

If shared, however, it can only be immutably dereferenced because there may be other references to the object, since a shared Id can be cloned to provide exactly that.

An Id<T, Owned> can be safely converted to a Id<T, Shared> using Id::into_shared or From/Into. The opposite is not safely possible, but the unsafe option Id::from_shared is provided.

Option<Id<T, O>> is guaranteed to have the same size as a pointer to the object.

Comparison to std types

Id<T, Owned> can be thought of as the Objective-C equivalent of Box from the standard library: It is a unique pointer to some allocated object, and that means you’re allowed to get a mutable reference to it.

Likewise, Id<T, Shared> is the Objective-C equivalent of Arc: It is a reference-counting pointer that, when cloned, increases the reference count.

Caveats

If the inner type implements Drop, that implementation will not be called, since there is no way to ensure that the Objective-C runtime will do so. If you need to run some code when the object is destroyed, implement the dealloc method instead.

This allows ?Sized types T, but the intention is to only support when T is an extern type (yet unstable).

Examples

use objc2::msg_send_id;
use objc2::runtime::{Class, Object};
use objc2::rc::{Id, Owned, Shared, WeakId};

let cls = Class::get("NSObject").unwrap();
let obj: Id<Object, Owned> = unsafe { msg_send_id![cls, new] };
// obj will be released when it goes out of scope

// share the object so we can clone it
let obj: Id<_, Shared> = obj.into();
let another_ref = obj.clone();
// dropping our other reference will decrement the retain count
drop(another_ref);

let weak = WeakId::new(&obj);
assert!(weak.load().is_some());
// After the object is deallocated, our weak pointer returns none
drop(obj);
assert!(weak.load().is_none());
let mut owned: Id<T, Owned>;
let mut_ref: &mut T = &mut *owned;
// Do something with `&mut T` here

let shared: Id<T, Shared> = owned.into();
let cloned: Id<T, Shared> = shared.clone();
// Do something with `&T` here

Implementations

Constructs an Id to an object that already has +1 retain count.

This is useful when you have a retain count that has been handed off from somewhere else, usually Objective-C methods like init, alloc, new, copy, or methods with the ns_returns_retained attribute.

Since most of the above methods create new objects, and you therefore hold unique access to the object, you would often set the ownership to be Owned.

But some immutable objects (like NSString) don’t always return unique references, so in those case you would use Shared.

Returns None if the pointer was null.

Safety

The caller must ensure the given object has +1 retain count, and that the object pointer otherwise follows the same safety requirements as in Id::retain.

Example
let cls: &Class;
let obj: &mut Object = unsafe { msg_send![cls, alloc] };
let obj: Id<Object, Owned> = unsafe { Id::new(msg_send![obj, init]).unwrap() };
// Or utilizing `msg_send_id`:
let obj = unsafe { msg_send_id![cls, alloc] };
let obj: Id<Object, Owned> = unsafe { msg_send_id![obj, init] };
// Or in this case simply just:
let obj: Id<Object, Owned> = unsafe { msg_send_id![cls, new] };
let cls = class!(NSString);
// NSString is immutable, so don't create an owned reference to it
let obj: Id<NSString, Shared> = unsafe { msg_send_id![cls, new] };

Returns a raw pointer to the object.

The pointer is valid for at least as long as the Id is held.

See Id::as_mut_ptr for the mutable equivalent.

This is an associated method, and must be called as Id::as_ptr(obj).

Returns a raw mutable pointer to the object.

The pointer is valid for at least as long as the Id is held.

See Id::as_ptr for the immutable equivalent.

This is an associated method, and must be called as Id::as_mut_ptr(obj).

Convert the type of the given object to another.

This is equivalent to a cast between two pointers.

See Id::into_super for a safe alternative.

This is common to do when you know that an object is a subclass of a specific class (e.g. casting an instance of NSString to NSObject is safe because NSString is a subclass of NSObject).

All 'static objects can safely be cast to Object, since that assumes no specific class.

Safety

You must ensure that the object can be reinterpreted as the given type.

If T is not 'static, you must ensure that U ensures that the data contained by T is kept alive for as long as U lives.

Additionally, you must ensure that any safety invariants that the new type has are upheld.

Retains the given object pointer.

This is useful when you have been given a pointer to an object from some API, and you would like to ensure that the object stays around so that you can work with it.

If said API is a normal Objective-C method, you probably want to use Id::retain_autoreleased instead.

This is rarely used to construct owned Ids, see Id::new for that.

Returns None if the pointer was null.

Safety

The caller must ensure that the ownership is correct; that is, there must be no Owned pointers or mutable references to the same object, and when creating owned Ids, there must be no other pointers or references to the object.

Additionally, the pointer must be valid as a reference (aligned, dereferencable and initialized, see the std::ptr module for more information).

Finally, if you do not know the concrete type of T, it may not be 'static, and hence you must ensure that the data that T references lives for as long as T.

Retains a previously autoreleased object pointer.

This is useful when calling Objective-C methods that return autoreleased objects, see Cocoa’s Memory Management Policy.

This has exactly the same semantics as Id::retain, except it can sometimes avoid putting the object into the autorelease pool, possibly yielding increased speed and reducing memory pressure.

Note: This relies heavily on being inlined right after msg_send!, be careful not accidentally require instructions between these.

Safety

Same as Id::retain.

Autoreleases and prepares the Id to be returned to Objective-C.

The object is not immediately released, but will be when the innermost autorelease pool is drained.

This is useful when declaring your own methods where you will often find yourself in need of returning autoreleased objects to properly follow Cocoa’s Memory Management Policy.

To that end, you could use Id::autorelease, but that would require you to have an AutoreleasePool object at hand, which you clearly won’t have in such cases. This function doesn’t require a pool object (but as a downside returns a pointer instead of a reference).

This is also more efficient than a normal autorelease, it makes a best effort attempt to hand off ownership of the retain count to a subsequent call to objc_retainAutoreleasedReturnValue / Id::retain_autoreleased in the enclosing call frame. Note: This optimization relies heavily on this function being tail called, so be careful to call this function at the end of your method.

Examples
use objc2::{class, msg_send_id, sel};
use objc2::declare::ClassBuilder;
use objc2::rc::{Id, Owned};
use objc2::runtime::{Class, Object, Sel};

let mut builder = ClassBuilder::new("ExampleObject", class!(NSObject)).unwrap();

extern "C" fn get(cls: &Class, _cmd: Sel) -> *mut Object {
    let obj: Id<Object, Owned> = unsafe { msg_send_id![cls, new] };
    obj.autorelease_return()
}

unsafe {
    builder.add_class_method(
        sel!(get),
        get as extern "C" fn(_, _) -> _,
    );
}

let cls = builder.register();

Autoreleases the owned Id, returning a mutable reference bound to the pool.

The object is not immediately released, but will be when the innermost / current autorelease pool (given as a parameter) is drained.

Promote a shared Id to an owned one, allowing it to be mutated.

Safety

The caller must ensure that there are no other pointers (including WeakId pointers) to the same object.

This also means that the given Id should have a retain count of exactly 1 (except when autoreleases are involved).

In general, this is wildly unsafe, do see if you can find a different solution!

Convert an owned to a shared Id, allowing it to be cloned.

This is also implemented as a From conversion, but this name is more explicit, which may be useful in some cases.

Autoreleases the shared Id, returning an aliased reference bound to the pool.

The object is not immediately released, but will be when the innermost / current autorelease pool (given as a parameter) is drained.

Convert the object into it’s superclass.

Trait Implementations

Converts this type into a mutable reference of the (usually inferred) input type.

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

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the contents of the internal buffer, filling it with more data from the inner reader if it is empty. Read more

Tells this buffer that amt bytes have been consumed from the buffer, so they should no longer be returned in calls to read. Read more

Read all bytes into buf until the delimiter byte or EOF is reached. Read more

Read all bytes until a newline (the 0xA byte) is reached, and append them to the provided buffer. You do not need to clear the buffer before appending. Read more

🔬This is a nightly-only experimental API. (buf_read_has_data_left)

Check if the underlying Read has any data left to be read. Read more

Returns an iterator over the contents of this reader split on the byte byte. Read more

Returns an iterator over the lines of this reader. Read more

Makes a clone of the shared object.

This increases the object’s reference count.

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Returns the “default value” for a type. Read more

Obtain an immutable reference to the object.

The resulting type after dereferencing.

Obtain a mutable reference to the object.

Formats the value using the given formatter. Read more

Removes and returns an element from the end of the iterator. Read more

Returns the nth element from the end of the iterator. Read more

🔬This is a nightly-only experimental API. (iter_advance_by)

Advances the iterator from the back by n elements. Read more

This is the reverse version of Iterator::try_fold(): it takes elements starting from the back of the iterator. Read more

An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. Read more

Searches for an element of an iterator from the back that satisfies a predicate. Read more

#[may_dangle] (see this) doesn’t apply here since we don’t run T’s destructor (rather, we want to discourage having Ts with a destructor); and even if we did run the destructor, it would not be safe to add since we cannot verify that a dealloc method doesn’t access borrowed data.

Releases the retained object.

The contained object’s destructor (if it has one) is never run!

The lower-level source of this error, if any. Read more

👎Deprecated since 1.42.0:

use the Display impl or to_string()

👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

🔬This is a nightly-only experimental API. (error_generic_member_access)

Provides type based access to context intended for error reports. Read more

Returns the exact remaining length of the iterator. Read more

🔬This is a nightly-only experimental API. (exact_size_is_empty)

Returns true if the iterator is empty. Read more

Extends a collection with the contents of an iterator. Read more

🔬This is a nightly-only experimental API. (extend_one)

Extends a collection with exactly one element.

🔬This is a nightly-only experimental API. (extend_one)

Reserves capacity in a collection for the given number of additional elements. Read more

Extends a collection with the contents of an iterator. Read more

🔬This is a nightly-only experimental API. (extend_one)

Extends a collection with exactly one element.

🔬This is a nightly-only experimental API. (extend_one)

Reserves capacity in a collection for the given number of additional elements. Read more

Convert an owned to a shared Id, allowing it to be cloned.

Same as Id::into_shared.

Converts to this type from the input type.

The type of value produced on completion.

Attempt to resolve the future to a final value, registering the current task for wakeup if the value is not yet available. Read more

Feeds this value into the given Hasher. Read more

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

Returns the hash value for the values written so far. Read more

Writes some data into this Hasher. Read more

Writes a single u8 into this hasher.

Writes a single u16 into this hasher.

Writes a single u32 into this hasher.

Writes a single u64 into this hasher.

Writes a single u128 into this hasher.

Writes a single usize into this hasher.

Writes a single i8 into this hasher.

Writes a single i16 into this hasher.

Writes a single i32 into this hasher.

Writes a single i64 into this hasher.

Writes a single i128 into this hasher.

Writes a single isize into this hasher.

🔬This is a nightly-only experimental API. (hasher_prefixfree_extras)

Writes a length prefix into this hasher, as part of being prefix-free. Read more

🔬This is a nightly-only experimental API. (hasher_prefixfree_extras)

Writes a single str into this hasher. Read more

The type of the elements being iterated over.

Advances the iterator and returns the next value. Read more

Returns the bounds on the remaining length of the iterator. Read more

Returns the nth element of the iterator. Read more

🔬This is a nightly-only experimental API. (iter_next_chunk)

Advances the iterator and returns an array containing the next N values. Read more

Consumes the iterator, counting the number of iterations and returning it. Read more

Consumes the iterator, returning the last element. Read more

🔬This is a nightly-only experimental API. (iter_advance_by)

Advances the iterator by n elements. Read more

Creates an iterator starting at the same point, but stepping by the given amount at each iteration. Read more

Takes two iterators and creates a new iterator over both in sequence. Read more

‘Zips up’ two iterators into a single iterator of pairs. Read more

🔬This is a nightly-only experimental API. (iter_intersperse)

Creates a new iterator which places an item generated by separator between adjacent items of the original iterator. Read more

Takes a closure and creates an iterator which calls that closure on each element. Read more

Calls a closure on each element of an iterator. Read more

Creates an iterator which uses a closure to determine if an element should be yielded. Read more

Creates an iterator that both filters and maps. Read more

Creates an iterator which gives the current iteration count as well as the next value. Read more

Creates an iterator which can use the peek and peek_mut methods to look at the next element of the iterator without consuming it. See their documentation for more information. Read more

Creates an iterator that skips elements based on a predicate. Read more

Creates an iterator that yields elements based on a predicate. Read more

Creates an iterator that both yields elements based on a predicate and maps. Read more

Creates an iterator that skips the first n elements. Read more

Creates an iterator that yields the first n elements, or fewer if the underlying iterator ends sooner. Read more

An iterator adapter similar to fold that holds internal state and produces a new iterator. Read more

Creates an iterator that works like map, but flattens nested structure. Read more

Creates an iterator which ends after the first None. Read more

Does something with each element of an iterator, passing the value on. Read more

Borrows an iterator, rather than consuming it. Read more

Transforms an iterator into a collection. Read more

🔬This is a nightly-only experimental API. (iter_collect_into)

Collects all the items from an iterator into a collection. Read more

Consumes an iterator, creating two collections from it. Read more

🔬This is a nightly-only experimental API. (iter_is_partitioned)

Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return true precede all those that return false. Read more

An iterator method that applies a function as long as it returns successfully, producing a single, final value. Read more

An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. Read more

Folds every element into an accumulator by applying an operation, returning the final result. Read more

Reduces the elements to a single one, by repeatedly applying a reducing operation. Read more

🔬This is a nightly-only experimental API. (iterator_try_reduce)

Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. Read more

Tests if every element of the iterator matches a predicate. Read more

Tests if any element of the iterator matches a predicate. Read more

Searches for an element of an iterator that satisfies a predicate. Read more

Applies function to the elements of iterator and returns the first non-none result. Read more

🔬This is a nightly-only experimental API. (try_find)

Applies function to the elements of iterator and returns the first true result or the first error. Read more

Searches for an element in an iterator, returning its index. Read more

Returns the element that gives the maximum value from the specified function. Read more

Returns the element that gives the maximum value with respect to the specified comparison function. Read more

Returns the element that gives the minimum value from the specified function. Read more

Returns the element that gives the minimum value with respect to the specified comparison function. Read more

Converts an iterator of pairs into a pair of containers. Read more

Creates an iterator which copies all of its elements. Read more

Creates an iterator which clones all of its elements. Read more

🔬This is a nightly-only experimental API. (iter_array_chunks)

Returns an iterator over N elements of the iterator at a time. Read more

Sums the elements of an iterator. Read more

Iterates over the entire iterator, multiplying all the elements Read more

🔬This is a nightly-only experimental API. (iter_order_by)

Lexicographically compares the elements of this Iterator with those of another with respect to the specified comparison function. Read more

Lexicographically compares the elements of this Iterator with those of another. Read more

🔬This is a nightly-only experimental API. (iter_order_by)

Lexicographically compares the elements of this Iterator with those of another with respect to the specified comparison function. Read more

Determines if the elements of this Iterator are equal to those of another. Read more

🔬This is a nightly-only experimental API. (iter_order_by)

Determines if the elements of this Iterator are equal to those of another with respect to the specified equality function. Read more

Determines if the elements of this Iterator are unequal to those of another. Read more

Determines if the elements of this Iterator are lexicographically less than those of another. Read more

Determines if the elements of this Iterator are lexicographically less or equal to those of another. Read more

Determines if the elements of this Iterator are lexicographically greater than those of another. Read more

Determines if the elements of this Iterator are lexicographically greater than or equal to those of another. Read more

🔬This is a nightly-only experimental API. (is_sorted)

Checks if the elements of this iterator are sorted using the given comparator function. Read more

🔬This is a nightly-only experimental API. (is_sorted)

Checks if the elements of this iterator are sorted using the given key extraction function. Read more

Sends a message to self with the given selector and arguments. Read more

Sends a message to a specific superclass with the given selector and arguments. Read more

Sends a message to self with the given selector and arguments. Read more

Sends a message to a specific superclass with the given selector and arguments. Read more

This method returns an Ordering between self and other. Read more

Compares and returns the maximum of two values. Read more

Compares and returns the minimum of two values. Read more

Restrict a value to a certain interval. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason. Read more

This method returns an ordering between self and other values if one exists. Read more

This method tests less than (for self and other) and is used by the < operator. Read more

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

This method tests greater than (for self and other) and is used by the > operator. Read more

Formats the value using the given formatter.

Pull some bytes from this source into the specified buffer, returning how many bytes were read. Read more

Like read, except that it reads into a slice of buffers. Read more

Read all bytes until EOF in this source, placing them into buf. Read more

Read all bytes until EOF in this source, appending them to buf. Read more

Read the exact number of bytes required to fill buf. Read more

🔬This is a nightly-only experimental API. (can_vector)

Determines if this Reader has an efficient read_vectored implementation. Read more

🔬This is a nightly-only experimental API. (read_buf)

Pull some bytes from this source into the specified buffer. Read more

🔬This is a nightly-only experimental API. (read_buf)

Read the exact number of bytes required to fill cursor. Read more

Creates a “by reference” adaptor for this instance of Read. Read more

Transforms this Read instance to an Iterator over its bytes. Read more

Creates an adapter which will chain this stream with another. Read more

Creates an adapter which will read at most limit bytes from it. Read more

Seek to an offset, in bytes, in a stream. Read more

Returns the current seek position from the start of the stream. Read more

Rewind to the beginning of a stream. Read more

🔬This is a nightly-only experimental API. (seek_stream_len)

Returns the length of this stream (in bytes). Read more

The type returned in the event of a conversion error.

Performs the conversion.

Write a buffer into this writer, returning how many bytes were written. Read more

Like write, except that it writes from a slice of buffers. Read more

Flush this output stream, ensuring that all intermediately buffered contents reach their destination. Read more

Attempts to write an entire buffer into this writer. Read more

Writes a formatted string into this writer, returning any error encountered. Read more

🔬This is a nightly-only experimental API. (can_vector)

Determines if this Writer has an efficient write_vectored implementation. Read more

🔬This is a nightly-only experimental API. (write_all_vectored)

Attempts to write multiple buffers into this writer. Read more

Creates a “by reference” adapter for this instance of Write. Read more

Id<T, Owned> are Send if T is Send because they give the same access as having a T directly.

The Send implementation requires T: Sync because Id<T, Shared> give access to &T.

Additiontally, it requires T: Send because if T: !Send, you could clone a Id<T, Shared>, send it to another thread, and drop the clone last, making dealloc get called on the other thread, and violate T: !Send.

Id<T, Owned> are Sync if T is Sync because they give the same access as having a T directly.

The Sync implementation requires T: Sync because &Id<T, Shared> give access to &T.

Additiontally, it requires T: Send, because if T: !Send, you could clone a &Id<T, Shared> from another thread, and drop the clone last, making dealloc get called on the other thread, and violate T: !Send.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

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

The output that the future will produce on completion.

Which kind of future are we turning this into?

Creates a future from a value. Read more

The type of the elements being iterated over.

Which kind of iterator are we turning this into?

Creates an iterator from a value. Read more

🔬This is a nightly-only experimental API. (provide_any)

Data providers should implement this method to provide all values they are able to provide by using demand. Read more

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

Uses borrowed data to replace owned data, usually by cloning. Read more

Converts the given value to a String. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.