NexumDigital/Messages-for-Twitter — pull request #19 by chroman (2013-11-30 07:46:17+00:00)
Title: Refactoring

I've refactored some code and fixed that weird bug.

- **Animations stop working at random time:**

This kind of behaviors happens when you do UIKit stuff in the background thread. UIKit elements are not Thread-Safe, so UIKit should not be called from a secondary thread. Those bugs are very hard to catch since they do not always occur predictably. I highly recommend to use this snippet in order to track down UIKit access on threads other than main. https://gist.github.com/steipete/5664345

So, there are two options to solve this problem, use `dispatch_async` to update the UI on the main queue or just remove the UIKit stuff (In this case using a UIImageView is not necessary).

The UIKit stuff was there on `NexumUtil.m`, `UIImageView *imageView...`:
```obj-c
+ (UIImage *)imageWithRoundedCornersSize:(float)cornerRadius usingImage:(UIImage *)original {
UIImageView *imageView = [[UIImageView alloc] initWithImage:original];
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);
[[UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:cornerRadius] addClip];
[original drawInRect:imageView.bounds];
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return imageView.image;
}
```

- **Refactoring concurrency code:**
Actually after iOS 4.0 I can't find any single reason to use `performSelector:`, `performSelectorOnMainThread:` methods. If you need to do something in background, use GCD (It is safe for UI operations).
Using `performSelector...` methods is kind of manual threading in Cocoa. In general, you should this.
This is an interesting note about this http://blackpixel.com/blog/2013/11/performselectoronmainthread-vs-dispatch-async.html
Also, Apple wrote interesting stuff about this https://developer.apple.com/library/mac/documentation/General/Conceptual/ConcurrencyProgrammingGuide/ThreadMigration/ThreadMigration.html

So the new code to do a server request and update the UI is something like this:
```obj-c
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
// Task in background
[self doSomethingHardLikeParsingJSON];
dispatch_async(dispatch_get_main_queue(), ^ {
// Refresh the UI, UIKit must be done in the main thread
[self updateUI];
});
});
```

- **FastImageCache**

I didn't work with FastImageCache before but seems a powerful library to achieve this task. So definitely this could be the best way to go :-)