loading...

re: How does your language handle memory? VIEW POST

FULL DISCUSSION
 

pre-not-an-expert-warning

iOS has a pretty interesting (and arguably new) system for memory management. It's built on ARC (Automatic Reference Counting) which essentially gives every object an underlying counter that can be shifted based on when another object references it and certain methods.

To explicitly change the way ARC handles an object, it's common to see weak / strong when declaring a property. weak won't increment the counter, strong will.

I popped open CFRuntime.c out of curiosity. That's where CFGetRetainCount(...) is defined – a function that reads the number of references an object has and I saw this:

CFIndex CFGetRetainCount(CFTypeRef cf) {
    if (NULL == cf) { CRSetCrashLogMessage("*** CFGetRetainCount() called with NULL ***"); HALT; }
    uint32_t cfinfo = *(uint32_t *)&(((CFRuntimeBase *)cf)->_cfinfo);
    if (cfinfo & 0x800000) { // custom ref counting for object
        CFTypeID typeID = (cfinfo >> 8) & 0x03FF; // mask up to 0x0FFF
        CFRuntimeClass *cfClass = __CFRuntimeClassTable[typeID];
7.      uint32_t (*refcount)(intptr_t, CFTypeRef) = cfClass->refcount;
        if (!refcount || !(cfClass->version & _kCFRuntimeCustomRefCount) || (((CFRuntimeBase *)cf)->_cfinfo[CF_RC_BITS] != 0xFF)) {
            HALT; // bogus object
        }

*snip*

On line 7 there's a read to cfClass->refcount, cfClass is oftype CFRuntimeClass which is declared in the header (.h) and at its core, refcount looks like:

uint32_t (*refcount)(intptr_t op, CFTypeRef cf);

Before this new system of memory management, it used to be entirely manual. Before Apple came to the rescue, it was mandatory for programmers to retain and release objects. It was a trip and turned me away from iOS for years.

There's a ton to talk about when it comes to Apple and memory, here's some links if you care:

 

Same goes for Python's weakref:

A weak reference to an object is not enough to keep the object alive: when the only remaining references to a referent are weak references, garbage collection is free to destroy the referent and reuse its memory for something else. However, until the object is actually destroyed the weak reference may return the object even if there are no strong references to it.

A lot of runtimes implement the same ideas in slightly different ways :D

Code of Conduct Report abuse