memory management - Swift NSBlockOperation() Leak: cannot make NSBlockOperation() weak -
to avoid memory leak when using nsblockoperation in objective-c, have declare variable weak able reference block operation inside block (to cancel if needed), typically this:
__weak nsblockoperation *blockop = [nsblockoperation blockoperationwithblock:^{ if (blockop.cancelled) { ... } }];
but in swift, when try declare nsblockopeartion weak, nil.
weak var blockop = nsblockoperation()
without weak reference, fine except leaking little bit of memory each time. how can reference block inside block without leaking memory in swift?
you can use explicit capture list capture unowned reference operation. (this 1 of times i'd suggest using unowned references, since operation retained long block executing. if you're still uncomfortable guarantee, use weak
instead.)
let op = nsblockoperation() op.addexecutionblock { [unowned op] in print("hi") if op.cancelled { ... } }
note has split 2 lines, because variable can't referenced own initial value.
Comments
Post a Comment