Sunday, March 3, 2013

Add arbitrary data to ios uiWebView or any other object

Usually if you need to add arbitrary data to an ios object, you will use subclass and add the arbitrary data to the derived class.
However, for uiWebView, the document from Apple mentioned the class should not be subclass. There is a Tag property in UIView, but it can only store integer value, and can not be used to store NSDictionary or NSArray.
The rescue are objc_setAssociatedObject and objc_getAssociatedObject methods, which allow to associate any arbitrary data with another object, including uiWebView object. These methods may make the structure of your application difficult to understanding, but they are the only way to add arbitrary to an object if subclass is not available.

UIWebView thread issue

When using ios UIWebView control, few thread related issues need to be kept in mind to avoid errors.
1. executeJavaScriptWithReturnValueInternal can only be caused from main thread, and it will block the main thread
2. If the caller of executeJavaScriptWithReturnValueInternalis already in main thread, like the call is triggered by a button click, (ios ui event is handled in main thread), then it can be called directly. If the caller is in background thread, the method needs to be called by performSelectorOnMainThread to switch to main thread.
3. Although uiWebView is single threaded, it can send multiple async xmlhttpRequests, including the cachedResponseForRequest