This is where it gets tricky.

When you create a chunk of memory using 'UnsafeMutablePointer.memory()' or 
'alloc()', it's as if you are programming in C with 'malloc' and 'free'. The 
memory you create and the objects you put in that memory don't participate in 
ARC - the runtime will not track reference counts or automatically free the 
memory. The memory will live on forever unless you explicitly call 'dealloc()' 
later.
Check.

Using these APIs correctly is quite hard. If you're not careful you can leak 
memory (if you lose all pointers before you've had a chance to call dealloc), 
or access invalid memory (you called dealloc earlier, but somewhere else you 
later access that memory). In a lot of cases a good thing to do is to wrap your 
unsafe memory buffer inside a regular Swift class, only allow the buffer to be 
accessed or modified through that class, and have that class be responsible for 
deallocating the buffer when its deinit is called. This way, you tie the 
lifetime of that buffer to your Swift class and ARC handles the memory 
management for you.
Exactly what I’m doing right now. :) But I’m still a little afraid when using 
these types.



-- 
Adrian Zubarev
Sent with Airmail
_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to