TExcelTAD
Home › Objective-C › Structs & C Interop

Structs & C Interop

Because Objective-C is C, you can mix objects freely with C structs, arrays, functions and libraries. Foundation itself uses small C structs for geometry and ranges, because they're cheaper than objects.

Foundation structs

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSRange r = NSMakeRange(4, 5);
        NSString *text = @"The quick fox";
        NSLog(@"range %lu..%lu -> '%@'", (unsigned long)r.location,
              (unsigned long)NSMaxRange(r) - 1, [text substringWithRange:r]);
        NSLog(@"contains 6? %d", NSLocationInRange(6, r));

        NSPoint p = NSMakePoint(10, 20);
        NSSize s = NSMakeSize(300, 150);
        NSRect frame = NSMakeRect(p.x, p.y, s.width, s.height);
        NSLog(@"frame at (%.0f, %.0f), size %.0f x %.0f", frame.origin.x, frame.origin.y,
              frame.size.width, frame.size.height);
        NSLog(@"max x %.0f, mid y %.0f", NSMaxX(frame), NSMidY(frame));
        NSLog(@"point inside? %d", NSPointInRect(NSMakePoint(50, 60), frame));
    }
    return 0;
}
range 4..8 -> 'quick'
contains 6? 1
frame at (10, 20), size 300 x 150
max x 310, mid y 95
point inside? 1

On iOS, the same structs are called CGPoint, CGSize and CGRect (from Core Graphics, created with CGRectMake and friends); on macOS NSRect and CGRect are the same type.

Your own structs

Structs are value types: assigning one copies all its fields. They're ideal for small bundles of numbers:

objc · try it yourself
#import <Foundation/Foundation.h>

typedef struct {
    double latitude;
    double longitude;
} Coordinate;

static inline Coordinate CoordinateMake(double lat, double lon) {
    Coordinate c = {lat, lon};
    return c;
}

double DistanceKm(Coordinate a, Coordinate b) {
    const double R = 6371.0;
    double dLat = (b.latitude - a.latitude) * M_PI / 180;
    double dLon = (b.longitude - a.longitude) * M_PI / 180;
    double h = sin(dLat / 2) * sin(dLat / 2) +
               cos(a.latitude * M_PI / 180) * cos(b.latitude * M_PI / 180) * sin(dLon / 2) * sin(dLon / 2);
    return 2 * R * asin(sqrt(h));
}

int main(void) {
    @autoreleasepool {
        Coordinate paris = CoordinateMake(48.8566, 2.3522);
        Coordinate berlin = {.latitude = 52.52, .longitude = 13.405};   // designated initializer

        Coordinate copy = paris;          // a full copy
        copy.latitude = 0;
        NSLog(@"paris.latitude still %.4f", paris.latitude);
        NSLog(@"Paris -> Berlin: %.0f km", DistanceKm(paris, berlin));
    }
    return 0;
}
paris.latitude still 48.8566
Paris -> Berlin: 877 km

Structs in collections: NSValue

Collections hold objects only, so structs are boxed with NSValue (or with @( ) for structs marked boxable). Foundation has helpers for its own structs:

objc · try it yourself
#import <Foundation/Foundation.h>

typedef struct { NSInteger row; NSInteger col; } Cell;

int main(void) {
    @autoreleasepool {
        NSArray *ranges = @[[NSValue valueWithRange:NSMakeRange(0, 3)],
                            [NSValue valueWithRange:NSMakeRange(10, 2)]];
        for (NSValue *v in ranges) {
            NSRange r = v.rangeValue;
            NSLog(@"range at %lu, length %lu", (unsigned long)r.location, (unsigned long)r.length);
        }

        // Any struct: store its bytes together with a type encoding
        Cell start = {2, 5};
        NSValue *boxed = [NSValue valueWithBytes:&start objCType:@encode(Cell)];
        Cell back;
        [boxed getValue:&back];
        NSLog(@"cell row %ld col %ld", (long)back.row, (long)back.col);
        NSLog(@"type encoding: %s", @encode(Cell));
    }
    return 0;
}
range at 0, length 3
range at 10, length 2
cell row 2 col 5
type encoding: {?=qq}

@encode(Type) produces the runtime's string description of a type, used by NSValue to remember what it holds. In {?=qq}, the braces mean a struct, ? that it has no tag name (it was declared with typedef struct { … }), and each q a 64-bit integer (NSInteger).

Objects inside structs, C arrays and C strings

Under ARC, a struct may contain object pointers in recent clang versions, but it's simpler to keep objects in classes and structs for plain data. Converting between C strings and NSString, and using C library functions, is routine:

objc · try it yourself
#import <Foundation/Foundation.h>
#include <ctype.h>

int compareInts(const void *a, const void *b) {
    return *(const int *)a - *(const int *)b;
}

int main(void) {
    @autoreleasepool {
        // C array sorted with the C library's qsort
        int scores[] = {72, 95, 61, 88};
        qsort(scores, 4, sizeof(int), compareInts);
        NSMutableArray *boxed = [NSMutableArray array];
        for (int i = 0; i < 4; i++) [boxed addObject:@(scores[i])];
        NSLog(@"sorted: %@", [boxed componentsJoinedByString:@" "]);

        // NSString -> C string -> processed with C -> NSString
        NSString *title = @"objective-c interop";
        const char *c = title.UTF8String;
        char buffer[64];
        size_t n = strlen(c);
        for (size_t i = 0; i < n && i < sizeof(buffer) - 1; i++) {
            buffer[i] = (char)toupper((unsigned char)c[i]);
        }
        buffer[MIN(n, sizeof(buffer) - 1)] = '\0';
        NSLog(@"%@", [NSString stringWithUTF8String:buffer]);

        // malloc'd memory is not managed by ARC
        double *samples = malloc(3 * sizeof(double));
        samples[0] = 1.5; samples[1] = 2.5; samples[2] = 3.5;
        NSLog(@"middle sample %.1f", samples[1]);
        free(samples);
    }
    return 0;
}
sorted: 61 72 88 95
OBJECTIVE-C INTEROP
middle sample 2.5

Note: The const char * from UTF8String is owned by the string and only valid while the string is alive. Copy it (e.g. with strdup) if you need to keep it longer.

Toll-free bridging

On Apple platforms, many Foundation classes share their memory layout with Core Foundation C types: NSString * ↔ CFStringRef, NSArray * ↔ CFArrayRef, NSData * ↔ CFDataRef. You cast between them with bridging casts that tell ARC who owns the object:

objc
CFStringRef cf = (__bridge CFStringRef)nsString;           // no ownership change
NSString *ns = (__bridge_transfer NSString *)CFStringCreateCopy(NULL, cf);  // ARC takes ownership
CFStringRef owned = (__bridge_retained CFStringRef)nsString;               // you must CFRelease
CFRelease(owned);

Test yourself

What happens when you assign one struct variable to another?

  1. Both point to the same struct
  2. All fields are copied
  3. Only the first field is copied
  4. It's not allowed

How do you store an NSRange in an NSArray?

  1. Directly
  2. Box it in an NSValue
  3. Convert to NSString
  4. Use NSNumber

Is memory from malloc released by ARC?

  1. Yes
  2. No, call free()
  3. Only inside @autoreleasepool
  4. Only for structs