Swift ARC and blocks - ios

I'm trying a simple example as seen here:
https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-XID_88
And this is my code. (Ignore other possible code, this is a empty project with this code written inside an empty UIViewcontroller viewDidLoad)
dispatch_async(dispatch_get_main_queue()) {
[unowned self] in
println(self)
}
I don't understand why it crashes when I run the pro
thread #1: tid = 0x1a796, 0x00284d18 libswiftCore.dylib`_swift_release_slow + 8, queue =
'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1,
address=0x458bc681)
Did something changed on the latest beta(5) and this is not supported anymore?
Thanks
edit:
Interesting that this code works on Objc
__weak MyViewController *weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"%#", weakSelf);
});
edit2:
The explanation on this link : Shall we always use [unowned self] inside closure in Swift on the difference of weak and unowned is wrong.
It's not just that weak nils and unowned doesn't. If that's the case, this should crash as well:
dispatch_async(dispatch_get_main_queue()) {
[weak self] in
println(self)
}
but it doesn't, and it prints the pointer, so, it's not nil.

[Unowned self] makes it so the closure does not create a strong reference to self and it does not automatically set it to nil if it gets deallocated either. By the time the async method is executed, self has been deallocated. That is why you are getting the crash.
It certainly doesn't make sense to use unowned in a one time asynchronous call. It would be better to capture a strong reference to it to be sure it sticks around. There still won't be a strong reference cycle because self does not own the closure.
Side Note: This cannot be all of your code as self isn't defined anywhere in your code.
unowned and weak are two different things. In Objective-C, unowned is called unsafe unretained. You can use weak in both languages. weak means that the runtime will automatically convert the reference to nil if the object is deallocated. unowned or unsafe unretained means that it will not be set to nil for you (which is why it is called "unsafe" in Objective-C.
Unowned should only ever be used in circumstances where the object will never be deallocated. In those circumstances, use weak.
Keep in mind, that if you capture a variable as weak in Swift, the reference will be made an optional so to use it you will have to unwrap it:
dispatch_async(dispatch_get_main_queue()) {
[weak self] in
if let actualSelf == self {
// do something with actualSelf
}
// you can still print the "wrapped" self because it is fine to print optionals
// even if they are `nil`
println(self)
}
But to be clear, it would still be best to use a strong reference in this circumstance:
dispatch_async(dispatch_get_main_queue()) {
println(self)
}

Related

If a UITableViewController captures self in a performBatchUpdates completion handler, can that cause a retain cycle?

Say I have a UITableViewController subclass which has some function in it, eg:
class MyTableVC: UITableViewController {
func doSomething() { ... }
}
and I add a function to it that calls performBatchUpdates with a completion handler which captures self:
func updateStuff() {
tableView.performBatchUpdates(someUpdates, completion: { _ in
self.doSomething()
}
}
Is there a danger of creating a retain cycle? If so, is the view controller guaranteed to be non-nil in the callback? i.e. If there's a possibility of a retain cycle, can I use [unowned self] or is it necessary to use [weak self]
There is no major issue in your solution. self will only be retained until the completion of batch update which is fine. And I'd probably do the same not to complicate the code.
Regularly it is a bit better to still have weak or unowned just to maintain similar code style through your project.
If you decide to pick one of these, weak is the only safe option here. For example, the view controller can be removed from the screen and deallocated while the table performs the update operation (the chance is really tiny but still exists) which will cause a crash in the result.

iOS + React Native - memory leaks

I'm considering making an iOS project in React Native. On iOS it's a big issue to find and fix so-called "retain cycles", i.e. when the two object store a strong reference to each other:
class Obj1 {
var delegate: Obj2?
}
class Obj2 {
var delegate: Obj1?
}
let obj1 = Obj1()
let obj2 = Obj2()
obj1.delegate = obj2
obj2.delegate = obj1
Does the React Native has a concept of a memory leak or retain cycle? Would the similar code in the JS counterpart create a retain cycle in React Native environment?
How about passing a closure capturing self? Would that also create a memory leak in React Native?
Summary:
Would the listed sample code (rewritten to JS) cause a memory leak in RN?
Would capturing self in a closure cause a memory leak?
You shouldn't really have two objects retaining strong references to each other, the delegate pattern is usually handled by having one strong and one weak reference, where the delegate is the weak one.
Now onto your questions:
Probably, but someone else might give you a better answer since I'm not entirely sure about RN.
Yes and no, depending on how you go about it.
If you use strong self, then definitely there will be a memory leak:
{ _ in
self.doSomething()
}
Better way is to use either weak self:
{ [weak self] _ in
guard let self = self else { return }
self.doSomething()
}
or unowned self if you can guarantee self is available in the closure at all times:
{ [unowned self] _ in
self.doSomething()
}

Should an asynchronous swift function retain a strong reference to the object?

We implemented and extension to NSData that asynchronously persists the data to a URL.
Here is a short version of the function.
extension NSData {
func writeToURL1(url:NSURL, completion: () -> Void) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { [weak self] in
guard let strongSelf = self else { return }
strongSelf.writeToURL(url, atomically: true)
completion()
})
}
}
Here is how we use it:
var imageData = UIImageJPEGRepresentation(image, 0.8)
imageData?.writeToURL(someURL) { in ... }
The problem of course is if imageData gets deallocated before the write operation is completed strongSelf will be nil and the completion handler will never be called.
There are two solutions to that problem.
remove [weak self] (i.e. have a strong reference to self in writeToURL1.
reference imageData in the completion block (i.e. imageData?.writeToURL(someURL) { in imageData = nil ... })
What approach is more Swift friendly and what approach should we choose?
Thank you!
You should use a strong reference if you don't want the object to go away from under your feet (and doing so wouldn't create a reference cycle); a weak reference if you don't care if the object goes away from under your feet; an unowned reference if you need the object to be around, and have a strong guarantee that the object won't go away from under your feet, but a strong reference would create a cycle.
In your case, you care that the object might go away, because that means that you won't be able to save it. As you have no guarantee that something else will keep the object alive until that task is completed, you should use a strong reference.
Strong references to self in closures are a problem when you carry the closure around because it's easy to end up with a non-obvious reference cycle, but you know for a fact that the reference will be dropped right after the closure is executed, so it's not a problem here.
It sounds like you just want to strongly capture the reference to the NSData object, so removing the [weak self] is the easiest and best approach in my opinion. Usually, weak references are used to avoid retain cycles when capturing in a closure. However, you're not actually creating a retain cycle, simply a one way retain by capturing self in the block. The block is not retained by self, it's simply passed down the call stack into dispatch_async, where it is ultimately invoked and deallocated. So there is no retain cycle to avoid by using weak self, you just have a retain occur via the closure which is desirable. That is, you want to keep the data in memory until that closure is invoked.

Swift unwraps value as nil when in closure but successfully unwraps elsewhere in code?

So here is my code
func retrieveAndAssignHighScoreFromCloudKit() {
let high = highScore
database.fetchRecordWithID(getRecordID(high), completionHandler: { [weak self]
(record: CKRecord?, error: NSError?) in
if error != nil {
print(self!.highScore)
// blah blah blah...
}
So in the first line of this function I am able to call highScore and assign it to something else but inside the closure Xcode is forcing me to use "self!." and in doing so somehow unwraps an optional even though my calling it prior shows me that it is not nil. I am really confused and there are a ton of basic questions about unwrapping optionals as nil but none that I've found seem to pertain to this.
Thank you very much!
EDIT: Tried switching "weak" to "unowned" and I crash on the same line and get "Thread 3: EXC_BREAKPOINT" despite not having and breakpoints. This message is displayed in green on another screen and does not highlight that line
Closures are not executed immediately.
When you pass a closure to the fetchRecordWithID method, you are telling it to execute that code when the method finishes fetching data, which can take time.
So far so good, right?
In the closure's capture list, you tell it to capture self as a weak reference. What's the purpose of this? To avoid a strong reference cycle, of course. If you don't, self holds a strong reference to the closure, and the closure holds a strong reference to self. As a result, both the closure and self will not be deinitialized.
A weak reference to self in the closure guarantees that self is deinitialized when the strong reference to the closure is broken.
I hope I've explained this well.
So now, let's say the strong reference to the closure is broken. As I said, self would be deinitialized as a result. After that, the thing finishes fetching data and it is now executing the completionHandler closure! Since self is already nil at this point, your app will crash when it reaches print(self!.highScore).
In other words, a weak reference to self implies that self can be nil. You need to unwrap it.
EDIT:
Maybe images can explain this better. (black arrows are strong references, green arrows are weak ones)
At first, it's like this:
When the strong reference is broken...
self becomes nil:
You can simply do something like this:
if let score = self?.highScore {
print(score)
// blah blah blah
} else {
// do something else, or nothing
}
Or just this:
print(self?.highScore)
You can use a strong reference when trying to use self like this:
func retrieveAndAssignHighScoreFromCloudKit() {
let high = highScore
database.fetchRecordWithID(getRecordID(high), completionHandler: { [weak self]
(record: CKRecord?, error: NSError?) in
if error != nil {
guard let strongSelf = self else {
return
}
print(strongSelf.highScore)
// blah blah blah...
}
}
}

How is a strong retain cycle possible with async or static calls?

I am trying to grasp how I can recognize when a strong retain cycle is possible and requires me to use [weak/unowned self]. I've been burned by unnecessarily using [weak/unowned self] and the self was deallocated immediately before giving me a chance to use it.
For example, below is an async network call that refers to self in the closure. Can a memory leak happen here since the network call is made without storing the call it self into a variable?
NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!) {
(data, response, error) in
self.data = data
)
Here's another example using the NSNotificationCenter, where a call can be made later asynchronously:
NSNotificationCenter.defaultCenter().addObserverForName(
UIApplicationSignificantTimeChangeNotification, object: nil, queue: nil) {
[unowned self] _ in
self.refresh()
}
My question is in what cases is a strong retain cycle possible? If I am making an asynchronous call or static call that references self in a closure, does that make it a candidate for [weak/unowned self]? Thanks for shedding any light on this.
A retain cycle is a situation when two objects has a strong reference to each other.
You are working with static variables NSURLSession.sharedSession() & NSNotificationCenter.defaultCenter() and as you may remember:
A singleton object provides a global point of access to the resources
of its class...You obtain the global instance from a singleton class
through a factory method. The class lazily creates its sole instance
the first time it is requested and thereafter ensures that no other
instance can be created. A singleton class also prevents callers from
copying, retaining, or releasing the instance.
https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/Singleton.html
Your "self" instance (like the others) doesn't have a strong reference to singletons objects and its closures too, that's why you don't have to worry about retain cycle in your case.
Check this great article for more details:
https://digitalleaves.com/blog/2015/05/demystifying-retain-cycles-in-arc/
In a nutshell:
The retain cycle can happen in two cases.
Case 1:
When two instances hold a strong reference to each other. You have to solve this by marking one of them as weak.
Case 2: (Which is related to your questions)
If you assign a closure to a property of a class instance and the body of that closure captures the instance.
In your two examples, no need to use weak self at all as NSNotificationCenter nor NSURLSession are properties to your class instance. (Or in other meaning, you don't have strong references to them)
Check this example where I have to use weak self:
[self.mm_drawerController setDrawerVisualStateBlock:^(MMDrawerController *drawerController, MMDrawerSide drawerSide, CGFloat percentVisible) {
if (drawerSide == MMDrawerSideRight && percentVisible == 1.0) {
[weakself showOverlayBgWithCloseButton:YES];
}
else{
[weakself hideOverlayBg];
}
}];
I have a strong reference to mm_drawerController and I assign a closure to it right?. inside this closure I want to capture self. So the closure will have a strong reference to self !! which is a disaster. In that case you will have a retain cycle. To break this cycle, use weak self inside the closure.

Resources