Preface
The JavaScriptCore series is taking a pause for now because of its complexity and the amount of time it requires. I will come back to it later. This article collects a few problems I ran into during day-to-day iOS development.
Issue List
Launch Images
While building a video splash screen, I ran into an awkward problem:
every time the local video was loaded, there was a short black-screen
interval of roughly 0.2 seconds. This is closely related to
AVPlayer, and I suspect it has something to do with video
decoding. Unfortunately, because the implementation is closed source,
there is not much we can do directly.
1 | - (void)setupVideoPlayer |
A teammate later suggested a workaround: since the splash screen
appears after the launch image, place a UIImageView above
the splash-screen view controller during the black-screen interval. Its
image is the launch image. After that short interval passes, remove the
UIImageView. It is a reasonable solution, although the
black-screen duration still cannot be controlled precisely.
But then another problem appeared:
The launch images we see every day in development could not be found.
There were no launch-image resources in mainBundle.
Do we really need to add every launch image back into the project as ordinary resources? That felt brutal. Every image is large, there are 2x and 3x variants, and there are many sizes.
After some investigation, I found that there is still a way to obtain
the launch image. At this point it is no longer about getting a URL; we
can obtain the corresponding UIImage directly from
memory:
1 | + (NSString *)getLaunchImageName |
Are You Really Reusing Cells?
In iOS development, cell reuse is completely normal. But for complex cells, the number of internal elements is often uncertain. Each reused cell may need a series of logic checks, a suitable height calculation, and a relayout of its subviews. That greatly reduces the benefit of reuse.
To avoid that trouble, some implementations remove all subviews after obtaining a reused cell, then recreate subviews according to the new model data. It is convenient, but it brings performance problems.
Take the comic-bookstore page in QQReader as an example. Every time the cell receives data, it used to do this:
1 | - (void)setViewModel:(id<XXXViewModelDelegate>)viewModel |
Instrumentation showed that cellForRow accounted for as
much as 17.6% of the time:

I then adjusted the comic-bookstore cell logic according to these principles:
- Reuse the cell, and create each subview in the cell only once.
- Create subviews lazily, only when they are actually needed.
- When the reused cell has more subviews than the current data needs, hide the redundant ones.
- For each network response, calculate each data model’s height only once, then cache and reuse it. After a refresh, discard all model data and cached heights.
After that, instrumentation showed that cellForRow
dropped to 7.5%:

So do not underestimate the performance cost of creating views.
Screen Size Can Lie
The project previously used this macro to detect iPhone X:
1 |
At first glance, the code looked fine, and it had worked on iPhone X. But when Apple released iPhone XS, iPhone XR, and iPhone XS Max, the problem arrived.
All three new devices have a notch, and the notch height is consistent. UI adaptation is essentially the same as iPhone X, so the habitual fix was to keep adding sizes to the macro:
1 |
At this point, IS_IPHONEX no longer really meant iPhone
X. It meant a family of notched-screen devices.
Then on a new iPhone XR, the macro kept returning NO.
After setting a breakpoint, I found that the device reported this screen
size:
(width = 750, height = 1624)
That was mildly worldview-breaking. Did someone sell us a fake iPhone XR?
After some confusion, someone finally remembered Display Zoom. I checked Settings, and sure enough, that was the reason.
So we added two more sizes for iPhone XR and iPhone XS Max after confirming they would not conflict with other models:
1 | (width = 750, height = 1624) iPhone XR in Display Zoom mode |
But this solution has serious flaws:
- The code becomes bulky and tedious, and it is easy to miss cases. Many devices support Display Zoom: iPhone 6/6s, iPhone 7/7s, iPhone 8/8s, iPhone XR, and iPhone XS Max.
- If the zoomed size of a notched device A happens to match the normal size of a non-notched device B, the macro becomes invalid. Even if that does not happen today, it could happen with a future non-notched device.
One teammate proposed this solution:
1 |
This is much simpler. It uses the safe area introduced for irregular screens, and it is a fairly elegant solution.
There is one drawback: before the window is created, this
macro cannot be used. For example, if you need to check
IS_IPHONEX inside load, this macro cannot
help.
In practice, screens can lie, but the device model will not. The following method is simpler and more accurate:
1 | - (NSString *)platform { |
1 | - (BOOL)isPhoneX |
Now Display Zoom no longer needs to be scary.
A Horizontal Table View
Normally, UITableView can implement sticky section
headers with simple configuration. But if you want a horizontal
UITableView-like layout with sticky headers, things are not
that easy. You need to rely on UICollectionView and
implement the sticky behavior yourself.
The main implementation here is
QRHorizontalFloatingHeaderLayout. It inherits from
UICollectionViewLayout. Usage is straightforward:
1 | QRHorizontalFloatingHeaderLayout *layout = [[QRHorizontalFloatingHeaderLayout alloc] init]; |
After that, implement the delegate methods in
QRHorizontalFloatingHeaderLayoutDelegate.
QRHorizontalFloatingHeaderLayout is implemented in
Objective-C, mainly based on this Swift version:
https://github.com/cruzdiego/HorizontalFloatingHeaderLayout
The core of the implementation is locating the
FloatingHeader coordinates during scrolling. The key
interface and layout flow look like this:
1 | @protocol QRHorizontalFloatingHeaderLayoutDelegate <NSObject> |
The Objective-C implementation is:
1 |
|
How Can a C++ Container Store Objective-C Objects?
In everyday iOS development, the most commonly used containers are
probably NSArray and NSDictionary. But in
scenarios with stricter performance requirements, these containers can
become insufficient. Many people choose Objective-C++ so they can use
powerful C++ libraries such as STL.
The tricky part is that Objective-C object memory management is more troublesome than ordinary C++ object management. If an Objective-C object is placed directly into an STL container, the container will not manage it by default. We need to retain and release it manually.
Here I directly quote duboleon’s solution under MRC:
1 | class ns_handle |
- With
retain, the original Objective-C object’s reference count is incremented when the handle is constructed and decremented when the handle is destroyed.- With
copy, the Objective-C object must conform toNSCopyingand implementcopyWithZone:.- With
assign, only assignment is performed.- By overloading
operator*,*handlecan be used to retrieve the Objective-C object stored inside the handle.
Usage:
1 | NSString * s = @"Test"; |
Then comes the next question: how should this be solved under ARC? The key is figuring out how to retain and release under ARC.
- How do we retain and release under ARC?
The first thought was objc_retain and
objc_release, but the runtime does not expose these
interfaces publicly. So that path was rejected. The next option is to
use bridging modifiers: __bridge_retained,
__bridge_transfer, and __bridge.
Retain an object under ARC:
1 | void *retainedThing = (__bridge_retained void *)obj; |
Release an object under ARC:
1 | void *retainedThing = (__bridge void *)obj; |
Use macros to handle ARC and MRC consistently:
1 |
- ARC does not handle C++ references
&very gracefully here, so change the return value fromid&toid.
1 | // Before |
After solving these two issues, the adjusted code is:
1 |
|
UIButton Highlight Delay in UIScrollView
During development, I noticed that a UIButton inside a
UITableViewCell had a delayed highlight. The reason is:
When a finger touches the content of a UIScrollView, the
following sequence occurs:
- The touch event is intercepted, and
trackingbecomesYES. - An internal timer starts, with a default interval of 150 ms. It checks whether the finger moves within a very short time window.
- If movement is detected in that interval,
UIScrollViewstarts scrolling by itself,trackingbecomesNO, and even if there is an internal control under the touch that could respond, it will no longer receive the touch event. - If no movement is detected in that interval,
trackingremainsYES; if there is an internal control under the finger that can respond to touch events, the event is passed to that control.
This can be fixed through delaysContentTouches:
1 | self.tableView.delaysContentTouches = NO; |
The Unruly UITableViewCell
Recently, while building a color tag, I thought using
UILabel would be convenient. Unexpectedly, it caused
trouble inside UITableViewCell. The reason is that
UITableViewCell changes the background color of its
subviews when highlighted:

But sometimes this is not the effect we want.
After looking through some references, I found one solution.
The main idea is to swizzle UITableViewCell’s
setHighlighted:animated: method and UILabel’s
setBackgroundColor: method. When the
UITableViewCell becomes highlighted, update the label’s
forbidSetBackgroundColor flag to control whether its
background color can be changed.
1 | // UITableViewCell+CellClick.m |
1 | // UILabel+CellClick.m |
This solution feels too heavy. Paying such a high cost for a small
background-color issue is not really worth it. Every
UITableViewCell calls setBackgroundColor:
during initialization, and the solution also introduces an invasive
property, firbidSetBackgroundColorWhenHighlighted, which
external code must set to indicate whether this logic should run.
Most importantly, it does not solve the problem completely. Although
it avoids UITableViewCell’s highlight logic, some custom
controls in the project also have their own highlight logic and still
cannot escape the same problem. So this is not a perfect solution.
The root cause is that we cannot control when a view’s
setBackgroundColor: method is called.
How can we defuse this?
What if we implement a custom control and explicitly control who is
allowed to call setBackgroundColor:?
Take QRCellLabel as an example.
- Define an internal class,
QRCellInnerLabel, inherited fromUILabel. Add ashouldSetBackgroundColorproperty to control whethersetBackgroundColor:is allowed.
1 | @interface QRCellInnerLabel : UILabel |
- Define a
QRCellLabelclass that mirrors commonUILabelproperties for convenient use. At compile time, forbid direct calls tosetBackgroundColor:and expose a customqr_setBackgroundColor:method.
1 | @interface QRCellLabel : UIView |
QRCellLabelcontains two subviews: aUIImageViewand aQRCellInnerLabel. The former is used for the background color, while the latter is used for text.
The implementation strategy is:
- Implement
setBackgroundColor:as an empty method. Even if outside code calls it, the control’s background color will not change.- In
qr_setBackgroundColor:, turn onshouldSetBackgroundColor, setQRCellInnerLabel’s background color, then immediately turnshouldSetBackgroundColoroff. This way the control’s background color can only be changed through the method it exposes.
1 | @implementation QRCellLabel |
With this approach, no matter which parent view contains the control, its background color cannot be changed without permission.
Lottie Pitfalls
I ran into several issues while using Lottie for animation recently. Here is a brief record.
- Cache issue
When using Lottie animations, we usually package the JSON file and asset files into a bundle for easier handling.
Suppose there are two Lottie files like this. Apart from the bundle names, the JSON file names and resource names inside are identical:
1 | _leftAnimationBundle = [NSBundle bundleWithURL:[NSBundle.mainBundle URLForResource:@"left_animation" withExtension:@"bundle"]]; |
When loading them, I found that the second Lottie animation always
rendered exactly like the first one. After tracing the source code, I
found the clue: animationName is used as the cache
key, and it only uses the JSON file name. If the JSON file name in the
second bundle has already appeared, Lottie skips loading and directly
uses the cache.
1 | // LOTComposition.m |
This is obviously not very reasonable. There is no good reason to force developers to ensure that JSON file names are unique across different bundles.
If the bundle file name is also included as part of the key, the
problem can be solved. The modification creates a new
animationKey by combining the JSON file name and the bundle
file name:
1 | // LOTComposition.m |
- Callback issue
Because the project needed callback handling after a Lottie animation finished, I initially used this API:
1 | - (void)playWithCompletion:(nullable LOTAnimationCompletionBlock)completion; |
But no callback was triggered. This issue also exists in the project tracker.
Later, I set the callback directly, set loopAnimation to
NO, and then called play. The callback
worked:
1 | _leftAnimationView.loopAnimation = NO;// If set to YES, it keeps playing and no completion callback is triggered. |
But then another requirement appeared: the animation needed to play
twice continuously before the final callback. Lottie does not provide
such an API, so the workaround is to call play again inside
the callback:
1 | @weakify(self) |
I thought that should solve it, but I was still too optimistic. The second callback never came back.
After tracing the source, I found that the callback is set to
nil after being called once:
1 | // LOTAnimationView.m |
I do not fully understand the author’s intention here. Maybe it was
to avoid block-related memory issues. For now, commenting out
self.completionBlock = nil solved the problem.
UIImageView Reuse
QQReader previously had an issue where book covers on the bookshelf
would occasionally appear in the wrong place. I always thought it was
caused by cell reuse. But after a long investigation, I found that
before each cell reuse, the UIImageView’s
image property was already being set to nil,
so it felt like this should not happen. I even suspected the refresh
mechanism for a while. I was naive.
Recently, I finally located the real problem.
Suppose a cell starts loading cover URL A. Before the network request returns, the cell is reused and starts loading cover URL B. But URL B returns earlier than URL A, or a local cover is set. Finally, URL A’s request returns. Because the old request was not unbound from the image view, it still sets the image, so the cell that should display cover B ends up displaying cover A. That causes the cover mix-up.
This also explains why simply setting
UIImageView.image = nil before reuse is not enough.
- If the project uses
SDWebImage, call this method before reuse to unbind the current request:
1 | - (void)sd_cancelCurrentImageLoad |
If the project uses a custom image loader:
- If there is an unbinding mechanism, unbind before reuse.
- If there is no unbinding mechanism, after the network response returns, verify that the current
UIImageViewURL still matches the URL associated with the returned image data:
1 | if([self.imageUrl isEqualToString:imageFetchItem.key]) |
Summary
That is all for now. I will keep adding more notes later.