Created
October 6, 2017 08:58
-
-
Save dedecej/66c28d3290c63d588aea6ae4651da851 to your computer and use it in GitHub Desktop.
Reference counting demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
// Retain count of object | |
var object = NSObject() | |
CFGetRetainCount(object) | |
let nextObject = object | |
CFGetRetainCount(object) | |
func retainCount(of object: NSObject) { | |
CFGetRetainCount(object) | |
} | |
retainCount(of: object) | |
// Weak references | |
weak var weakObject = object | |
CFGetRetainCount(object) | |
do { | |
weakObject = NSObject() | |
} | |
weakObject | |
// Retain count of object in Array | |
let array = [NSObject()] | |
CFGetRetainCount(array[0]) | |
var newArray = array | |
CFGetRetainCount(array[0]) | |
newArray.append(NSObject()) | |
CFGetRetainCount(array[0]) | |
func retainCount(of objects: [NSObject]) { | |
CFGetRetainCount(objects[0]) | |
} | |
retainCount(of: array) | |
// Custom copy-on-write type | |
class _MagixBox<T> { | |
var value: T | |
init(value: T) { | |
self.value = value | |
} | |
} | |
struct MagicBox<T> { | |
var box: _MagixBox<T> | |
init(value: T) { | |
self.box = _MagixBox(value: value) | |
} | |
var value: T { | |
get { | |
return box.value | |
} | |
set { | |
if isKnownUniquelyReferenced(&box) { | |
box.value = newValue | |
} else { | |
box = _MagixBox(value: newValue) | |
} | |
} | |
} | |
} | |
var b = MagicBox(value: 0) | |
b.value | |
var b2 = b | |
b.value | |
b2.value = 10 | |
b.value = 1 | |
b2.value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment