NSValue

NSValue is a simple container for a single C or Objective-C data value. It can hold scalars and value types, as well as pointers and object IDs.

nshipster.com/nsvalue/

NSValue is the lightweight way to put any C scalar or struct (int, float, CGPoint, CGRect, NSRange, etc.) into an object so it can live in NSArray, NSDictionary, NSSet, etc.

Two methods stand out:

  1. +valueWithBytes:objCType:
    Boxes any value (even custom structs) if you give it the @encode() type string.
    Example: NSValue(value: &point, objCType: @encode(CGPoint))

  2. +valueWithNonretainedObject:
    Boxes a weak/non-retained object reference. Perfect when you need to store an object in a collection without retaining it and without requiring <NSCopying> (common with delegates, temporary keys, or objects that can’t be copied).

Bottom line: whenever you hit “can’t put X in NSArray/NSDictionary”, reach for NSValue, it’s the official, zero-cost magic box that bridges C values and the object world.


Category:

Year: