Is readonly property always “atomic”?

后端 未结 2 1733
天涯浪人
天涯浪人 2021-02-09 15:55

Sometimes we have a simple readOnly Property whose value may change

@property (readonly) NSFetchedResultsController * FetchController;
@property (readonly) NSFet         


        
2条回答
  •  独厮守ぢ
    2021-02-09 16:47

    I think you're misunderstanding what atomic (or more appropriately, nonatomic) means in this context. The simplest explanation can be found in objc-accessors.mm itself:

    id objc_getProperty_non_gc(id self, SEL _cmd, ptrdiff_t offset, BOOL atomic) {
        // Retain release world
        id *slot = (id*) ((char*)self + offset);
        if (!atomic) return *slot;
    
        // Atomic retain release world
        spin_lock_t *slotlock = &PropertyLocks[GOODHASH(slot)];
        _spin_lock(slotlock);
        id value = objc_retain(*slot);
        _spin_unlock(slotlock);
    
        // for performance, we (safely) issue the autorelease OUTSIDE of the spinlock.
        return objc_autoreleaseReturnValue(value);
    }
    

    As you can see, atomicity here refers only to the validity of the returned object. It it retained and autoreleased in order to guarantee that it does not get deallocated while you are using it.

    If this [[obj retain] autorelease] was not performed, another thread could set the property, which would cause the previous property (i.e. the one you're using) to be released and possibly deallocated.

提交回复
热议问题