Last active
October 6, 2017 08:56
-
-
Save novellizator/6f69167193e2ceb539e637d54c770d04 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 | |
let object = NSObject() | |
CFGetRetainCount(object) | |
let nextObject = object | |
CFGetRetainCount(object) | |
func retainCount(of object: NSObject) { | |
CFGetRetainCount(object) | |
} | |
retainCount(of: object) | |
// 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) | |
// copy on write | |
// 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