iOS Issue Notes

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (void)setupVideoPlayer
{
NSURL* fileUrl = [NSURL fileURLWithPath:@"local video url"];
AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:fileUrl options:nil];
AVPlayerItem * playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
self.player = [AVPlayer playerWithPlayerItem:playerItem];

self.moviePlayer = [[AVPlayerViewController alloc] init];
self.moviePlayer.showsPlaybackControls = NO;
self.moviePlayer.player = self.player;
self.moviePlayer.view.backgroundColor = self.view.backgroundColor;
[self.view addSubview:self.moviePlayer.view];
self.moviePlayer.view.frame = self.view.frame;
self.moviePlayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
+ (NSString *)getLaunchImageName
{
CGSize viewSize = [UIApplication sharedApplication].delegate.window.bounds.size;

NSString *viewOrientation = @"Portrait";
if(UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)){
viewOrientation = @"Landscape";
}

NSString *launchImageName = nil;
NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
for (NSDictionary* dict in imagesDict)
{
CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
{
launchImageName = dict[@"UILaunchImageName"];
}
}
return launchImageName;
}

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
2
3
4
5
6
7
8
9
10
11
12
- (void)setViewModel:(id<XXXViewModelDelegate>)viewModel
{
// Remove every subview from the cell each time the cell is reused.
[self.subviews enumerateObjectsUsingBlock:^(XXXSubView * _Nonnull obj,
NSUInteger idx,
BOOL * _Nonnull stop) {
[obj removeFromSuperview];
}];

// Then recreate subviews and assign data.
...
}

Instrumentation showed that cellForRow accounted for as much as 17.6% of the time:

Before optimization

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%:

After optimization

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
#define IS_IPHONEX                      ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO)

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
2
3
4
5
6
#define IS_IPHONEX                      ([UIScreen instancesRespondToSelector:@selector(currentMode)] ?\
(CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) ||\
CGSizeEqualToSize(CGSizeMake(1242, 2688), [[UIScreen mainScreen] currentMode].size) ||\
CGSizeEqualToSize(CGSizeMake(828, 1792) , [[UIScreen mainScreen] currentMode].size) )\
: NO)

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
2
(width = 750, height = 1624)  iPhone XR in Display Zoom mode
(width = 1125, height = 2436) iPhone XS Max in Display Zoom mode, same as normal iPhone X

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
2
3
4
5
6
#define IS_IPHONEX \
({BOOL isPhoneX = NO;\
if (@available(iOS 11.0, *)) {\
isPhoneX = [[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom > 0.0;\
}\
(isPhoneX);})

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
2
3
4
5
6
7
8
9
10
- (NSString *)platform {

size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char *machine = malloc(size);
sysctlbyname("hw.machine", machine, &size, NULL, 0);
NSString *platform = [NSString stringWithUTF8String:machine];
free(machine);
return platform;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
- (BOOL)isPhoneX
{
NSString* plat = [self platform];

if ([platform isEqualToString:@"iPhone10,3"] ||
[platform isEqualToString:@"iPhone10,6"]) {
// modelType = DeviceModelTypeIPhoneX
return YES;
}
else if([platform isEqualToString:@"iPhone11,2"]) {
// modelType = DeviceModelTypeIPhoneXS
return YES;
}
else if ([platform isEqualToString:@"iPhone11,4"] ||
[platform isEqualToString:@"iPhone11,6"]){
// modelType = DeviceModelTypeIPhoneXSMAX
return YES;
}
else if([platform isEqualToString:@"iPhone11,8"]){
// modelType = DeviceModelTypeIPhoneXR;
return YES;
}
return NO;
}

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
2
3
4
QRHorizontalFloatingHeaderLayout *layout = [[QRHorizontalFloatingHeaderLayout alloc] init];

_collectionView = [[UICollectionView alloc]initWithFrame:frame
collectionViewLayout:layout];

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@protocol QRHorizontalFloatingHeaderLayoutDelegate <NSObject>

// Item size
- (CGSize) collectionView:(UICollectionView*)collectionView horizontalFloatingHeaderItemSizeAt:(NSIndexPath*)indexPath;

// Header size
- (CGSize) collectionView:(UICollectionView*)collectionView horizontalFloatingHeaderSizeAt:(NSInteger)section;

// Section Inset
- (CGFloat) collectionView:(UICollectionView*)collectionView horizontalFloatingHeaderItemSpacingForSectionAt:(NSInteger)section;

// Item Spacing
- (CGFloat) collectionView:(UICollectionView *)collectionView horizontalFloatingHeaderColumnSpacingForSectionAt:(NSInteger)section;

// Line Spacing
- (UIEdgeInsets) collectionView:(UICollectionView*)collectionView horizontalFloatingHeaderSectionInsetAt:(NSInteger)section;

// Left Margin
- (CGFloat) collectionView:(UICollectionView*)collectionView horizontalFloatingHeaderLeftMarginForSectionAt:(NSInteger)section;
@end

@interface QRHorizontalFloatingHeaderLayout : UICollectionViewLayout

@end

The Objective-C implementation is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#import "QRHorizontalFloatingHeaderLayout.h"

@interface QRHorizontalFloatingHeaderLayout()
@property(nonatomic,strong)NSMutableDictionary* itemsAttributes;

@property(nonatomic,assign)CGFloat currentMinX;
@property(nonatomic,assign)CGFloat currentMinY;
@property(nonatomic,assign)CGFloat currentMaxX;
@end

@implementation QRHorizontalFloatingHeaderLayout

- (instancetype)init
{
if(self = [super init])
{
_itemsAttributes = [NSMutableDictionary dictionary];
_currentMaxX = 0;
_currentMinX = 0;
_currentMinY = 0;
}
return self;
}

- (CGSize)collectionViewContentSize
{
if(!self.collectionView){
return CGSizeZero;
}



UICollectionView* collectionView = self.collectionView;
NSInteger lastSection = collectionView.numberOfSections - 1;

if(lastSection < 0){
return CGSizeZero;
}

CGFloat contentWidth = self.lastItemMaxX + [self insetForSection:lastSection].right;
CGFloat contentHeight =
collectionView.bounds.size.height -
collectionView.contentInset.top -
collectionView.contentInset.bottom;

return CGSizeMake(contentWidth,contentHeight);
}

- (CGFloat)lastItemMaxX
{
UICollectionView* collectionView = self.collectionView;
NSInteger lastSection = collectionView.numberOfSections - 1;
NSInteger lastRow = [collectionView numberOfItemsInSection:lastSection] -1;
UICollectionViewLayoutAttributes* lastItemAttributes =
[self layoutAttributesForItemAtIndexPath:[NSIndexPath
indexPathForRow:lastRow inSection:lastSection]];
return lastItemAttributes ? CGRectGetMaxX(lastItemAttributes.frame) : 0;
}

- (UICollectionViewLayoutAttributes*)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSIndexPath* aIndexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
return self.itemsAttributes[aIndexPath];
}

- (UICollectionViewLayoutAttributes*)layoutAttributesForSupplementaryViewOfKind:(NSString *)elementKind
atIndexPath:(NSIndexPath *)indexPath
{
if([elementKind isEqualToString:UICollectionElementKindSectionHeader])
{
return [self.sectionHeadersAttributes qr_safeObjectForKey:indexPath];
}
return nil;
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
return true;
}

- (UICollectionViewLayoutInvalidationContext*)invalidationContextForBoundsChange:(CGRect)newBounds
{
UICollectionViewLayoutInvalidationContext* context = [super invalidationContextForBoundsChange:newBounds];
CGRect oldBounds = self.collectionView.bounds;

BOOL isSizeChanged =
oldBounds.size.width != newBounds.size.width ||
oldBounds.size.height != newBounds.size.height;
if(!isSizeChanged)
{
NSArray* headersIndexPaths = [self.sectionHeadersAttributes allKeys];
[context invalidateSupplementaryElementsOfKind:UICollectionElementKindSectionHeader
atIndexPaths:headersIndexPaths];
}
return context;
}

- (void)prepareLayout
{
[self prepareItemsAttributes];
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray<UICollectionViewLayoutAttributes *> * itemsA =
[self attributes:self.itemsAttributes containedInRect:rect];
NSArray<UICollectionViewLayoutAttributes *> * itemsB =
[self.sectionHeadersAttributes allValues];
return [itemsA arrayByAddingObjectsFromArray:itemsB];
}

#pragma mark - Private


- (NSMutableDictionary<NSIndexPath*,UICollectionViewLayoutAttributes*>*)sectionHeadersAttributes
{
UICollectionView* collectionView = self.collectionView;
NSInteger sectionCount = collectionView.numberOfSections;
if(!collectionView || sectionCount < 0)
{
return [NSMutableDictionary dictionary];
}

NSMutableDictionary<NSIndexPath*,UICollectionViewLayoutAttributes*>* attributes =
[NSMutableDictionary dictionary];
for (NSInteger section = 0; section < sectionCount; section++) {
NSIndexPath* indexPath = [NSIndexPath indexPathForRow:0 inSection:section];
UICollectionViewLayoutAttributes* attribute = [self attributeForSectionHeaderAtIndexPath:indexPath];
[attributes qr_safeSetObject:attribute forKey:indexPath];
}
return attributes;
}

- (UICollectionViewLayoutAttributes*)attributeForSectionHeaderAtIndexPath:(NSIndexPath*)indexPath
{
UICollectionViewLayoutAttributes* attribute =
[UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader
withIndexPath:indexPath];

UICollectionView* collectionView = self.collectionView;
CGSize mySize = [self headerSizeforSection:indexPath.section];

NSInteger itemsCount = [collectionView numberOfItemsInSection:indexPath.section];

UICollectionViewLayoutAttributes* firstItemAttribute = [self layoutAttributesForItemAtIndexPath:indexPath];
UICollectionViewLayoutAttributes* lastItemAttribute = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:itemsCount-1 inSection:indexPath.section]];

CGPoint myPosition;
CGFloat leftMargin = [self leftMarginForSection:indexPath.section];
if(itemsCount > 0 && firstItemAttribute && lastItemAttribute)
{
CGFloat edgeX = collectionView.contentOffset.x + collectionView.contentInset.left;
CGFloat xByLeftBoundary = MAX(edgeX+leftMargin, CGRectGetMinX(firstItemAttribute.frame));
CGFloat xByRightBoundary = CGRectGetMaxX(lastItemAttribute.frame) - mySize.width;
CGFloat x = MIN(xByLeftBoundary, xByRightBoundary);
myPosition = CGPointMake(x, 0);
}
else
{
CGFloat x = [self insetForSection:indexPath.section].left;
myPosition = CGPointMake(x, 0);
}

CGRect frame = CGRectMake(myPosition.x, myPosition.y, mySize.width, mySize.height);
attribute.frame = frame;
return attribute;
}

- (NSArray<UICollectionViewLayoutAttributes*>*)attributes:(NSDictionary*)attributes
containedInRect:(CGRect)rect
{
NSMutableArray<UICollectionViewLayoutAttributes*>* finalAttributes =
[NSMutableArray array];
for (UICollectionViewLayoutAttributes* attribute in attributes.allValues) {
if(CGRectIntersectsRect(rect, attribute.frame))
{
[finalAttributes qr_safeAddObject:attribute];
}
}
return finalAttributes;
}

- (void)prepareItemsAttributes
{

UICollectionView* collectionView = self.collectionView;
NSInteger sectionCount = collectionView.numberOfSections;
if(!collectionView || sectionCount <= 0){return;}

[self resetAttributes];

for (NSInteger section = 0; section < sectionCount; section++) {
[self configureVariablesforSection:section];
NSInteger itemCount = [collectionView numberOfItemsInSection:section];
if(itemCount <= 0){ continue;}
for (NSInteger row = 0; row < itemCount; row++) {
NSIndexPath* indexPath = [NSIndexPath indexPathForRow:row inSection:section];
UICollectionViewLayoutAttributes* attribute = [self itemAttributeAtIndexPath:indexPath];
[self.itemsAttributes qr_safeSetObject:attribute forKey:indexPath];
}
}

}

- (void)resetAttributes
{
[self.itemsAttributes removeAllObjects];
self.currentMinX = 0;
self.currentMaxX = 0;
self.currentMinY = 0;
}

- (void)configureVariablesforSection:(NSInteger)section
{
UIEdgeInsets sectionInset = [self insetForSection:section];
UIEdgeInsets lastSectionInset = [self insetForSection:section-1];
self.currentMinX = (self.currentMaxX + sectionInset.left + lastSectionInset.right);
self.currentMinY = sectionInset.top + [self headerSizeforSection:section].height;
self.currentMaxX = self.currentMinX;
}

- (UICollectionViewLayoutAttributes*)itemAttributeAtIndexPath:(NSIndexPath*)indexPath
{
CGSize size = [self itemSizeForIndexPath:indexPath];
CGFloat newMaxY = self.currentMinY + size.height;
CGPoint origin = CGPointZero;
if(newMaxY >= [self availableHeightAtSection:indexPath.section])
{
origin.x = self.currentMaxX + [self columnSpacingForSection:indexPath.section];
origin.y = [self insetForSection:indexPath.section].top + [self headerSizeforSection:indexPath.section].height;
}
else
{
origin.x = self.currentMinX;
origin.y = self.currentMinY;
}

CGRect frame = CGRectMake(origin.x, origin.y, size.width, size.height);
UICollectionViewLayoutAttributes* attribute =
[UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
attribute.frame = frame;

self.currentMaxX = MAX(self.currentMaxX,CGRectGetMaxX(frame));
self.currentMinX = CGRectGetMinX(frame);
self.currentMinY = CGRectGetMaxY(frame) + [self itemSpacingForSection:indexPath.section];

return attribute;
}

- (CGFloat)availableHeightAtSection:(NSInteger)section
{
if(!self.collectionView || section < 0){
return 0.0f;
}
UIEdgeInsets sectionInset = [self insetForSection:section];
UIEdgeInsets contentInset = self.collectionView.contentInset;
CGFloat totalInset = sectionInset.top + sectionInset.bottom + contentInset.top + contentInset.bottom;
return self.collectionView.bounds.size.height - totalInset;
}

- (CGSize)headerSizeforSection:(NSInteger)section
{
if(section < 0 || !self.collectionView)
{
return CGSizeZero;
}

id<QRHorizontalFloatingHeaderLayoutDelegate> delegate =
(id<QRHorizontalFloatingHeaderLayoutDelegate>)(self.collectionView.delegate);
if([delegate respondsToSelector:@selector(collectionView:horizontalFloatingHeaderSizeAt:)])
{
return [delegate collectionView:self.collectionView horizontalFloatingHeaderSizeAt:section];
}

return CGSizeZero;

}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class ns_handle
{
private:
typedef enum
{
_retain,
_assign,
_copy,
}_mem_type;

public:
static const _mem_type retain = _retain;
static const _mem_type assign = _assign;
static const _mem_type copy = _copy;

public:
ns_handle(id nsObj,_mem_type mem_type = retain);
ns_handle(const ns_handle & handle);
ns_handle & operator=(const ns_handle & handle);
id & operator*();
~ns_handle();

private:
id m_nsObj;
};

inline ns_handle::ns_handle(id nsObj,_mem_type mem_type):m_nsObj(nsObj)
{
switch (mem_type)
{
case retain:
[m_nsObj retain];
break;
case assign:
break;
case copy:
[m_nsObj copy];
break;
default:
break;
}
}

inline ns_handle::ns_handle(const ns_handle & handle):m_nsObj(handle.m_nsObj)
{
[m_nsObj retain];
}

inline ns_handle & ns_handle::operator=(const ns_handle & handle)
{
[m_nsObj release];
m_nsObj = handle.m_nsObj;
[m_nsObj retain];
return *this;
}

inline id & ns_handle::operator*()
{
return m_nsObj;
}

inline ns_handle::~ns_handle()
{
[m_nsObj release];
}
  • 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 to NSCopying and implement copyWithZone:.
  • With assign, only assignment is performed.
  • By overloading operator*, *handle can be used to retrieve the Objective-C object stored inside the handle.

Usage:

1
2
3
4
5
NSString * s = @"Test";
ns_handle handle(s,ns_handle::copy);
std::vector<ns_handle> vec;
vec.push_back(handle);
NSLog(@"%@",*handle);

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
2
void *retainedThing = (__bridge_retained void *)obj; 
retainedThing = retainedThing;

Release an object under ARC:

1
2
3
void *retainedThing = (__bridge void *)obj; 
id unretainedThing = (__bridge_transfer id)retainedThing;
unretainedThing = nil;

Use macros to handle ARC and MRC consistently:

1
2
3
4
5
6
7
#if __has_feature(objc_arc)
#define UniversalRetain(...) void *retainedThing = (__bridge_retained void *)__VA_ARGS__; retainedThing = retainedThing
#define UniversalRelease(...) void *retainedThing = (__bridge void *) __VA_ARGS__; id unretainedThing = (__bridge_transfer id)retainedThing; unretainedThing = nil
#else
#define UniversalRetain(...) [__VA_ARGS__ retain];
#define UniversalRelease(...) [__VA_ARGS__ release];
#endif
  • ARC does not handle C++ references & very gracefully here, so change the return value from id& to id.
1
2
3
4
5
6
7
8
9
10
11
// Before
inline id & ns_handle::operator*()
{
return m_nsObj;
}

// After
inline id ns_handle::operator*()
{
return m_nsObj;
}

After solving these two issues, the adjusted code is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#ifndef NSHandle_h
#define NSHandle_h

class ns_handle
{
private:
typedef enum
{
_retain,
_assign,
_copy,
}_mem_type;
public:
static const _mem_type retain = _retain;
static const _mem_type assign = _assign;
static const _mem_type copy = _copy;
public:
ns_handle(id nsObj,_mem_type mem_type = retain);
ns_handle(const ns_handle & handle);
ns_handle & operator=(const ns_handle & handle);

inline id operator*();

~ns_handle();
private:
id m_nsObj;
};
inline ns_handle::ns_handle(id nsObj,_mem_type mem_type):m_nsObj(nsObj)
{
switch (mem_type)
{
case retain:
{
UniversalRetain(m_nsObj);
}
break;
case assign:
break;
case copy:
[m_nsObj copy];
break;
default:
break;
}
}
inline ns_handle::ns_handle(const ns_handle & handle):m_nsObj(handle.m_nsObj)
{
UniversalRetain(m_nsObj);
}
inline ns_handle & ns_handle::operator=(const ns_handle & handle)
{
#if __has_feature(objc_arc)
m_nsObj = handle.m_nsObj;
#else
[m_nsObj release];
m_nsObj = handle.m_nsObj;
[m_nsObj retain];
#endif
return *this;
}

inline id ns_handle::operator*()
{
return m_nsObj;
}

inline ns_handle::~ns_handle()
{
UniversalRelease(m_nsObj);
}

#endif /* NSHandle_h */

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:

  1. The touch event is intercepted, and tracking becomes YES.
  2. An internal timer starts, with a default interval of 150 ms. It checks whether the finger moves within a very short time window.
  3. If movement is detected in that interval, UIScrollView starts scrolling by itself, tracking becomes NO, and even if there is an internal control under the touch that could respond, it will no longer receive the touch event.
  4. If no movement is detected in that interval, tracking remains YES; 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
2
3
4
5
6
self.tableView.delaysContentTouches = NO;
for (id obj in self.tableView.subviews) {
if ([obj respondsToSelector:@selector(setDelaysContentTouches:)]) {
[obj setDelaysContentTouches: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:

Before optimization

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// UITableViewCell+CellClick.m

- (void)qr_setHighlighted:(BOOL)highlighted animated:(BOOL)animated
{
if (highlighted)
{
[self setupInnerLabelForbidState:YES superView:self.contentView];
}
else
{
[self setupInnerLabelForbidState:NO superView:self.contentView];
}
[self qr_setHighlighted:highlighted animated:animated];
}

- (void)setupInnerLabelForbidState:(BOOL)forbid superView:(UIView*)superView
{
for (UIView *subview in superView.subviews)
{
if ([subview isKindOfClass:[UILabel class]])
{
// If firbidSetBackgroundColorWhenHighlighted is enabled,
// the label's background color is not allowed to change.
UILabel *label = (UILabel *)subview;
if(label.firbidSetBackgroundColorWhenHighlighted)
label.forbidSetBackgroundColor = forbid;
}
else if(subview.class.isCustomClass)
{
// Recursively traverse subviews.
[self setupInnerLabelForbidState:forbid superView:subview];
}
}
}
1
2
3
4
5
6
7
8
//  UILabel+CellClick.m
- (void)qr_setBackgroundColor:(UIColor *)backgroundColor
{
// If setting is not forbidden, call the original color-changing method.
if (!self.forbidSetBackgroundColor){
[self qr_setBackgroundColor:backgroundColor];
}
}

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.

  1. Define an internal class, QRCellInnerLabel, inherited from UILabel. Add a shouldSetBackgroundColor property to control whether setBackgroundColor: is allowed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@interface QRCellInnerLabel : UILabel
@property(nonatomic,assign) BOOL shouldSetBackgroundColor;
@end

@implementation QRCellInnerLabel
- (void)setBackgroundColor:(UIColor *)backgroundColor
{
if(_shouldSetBackgroundColor)
{
[super setBackgroundColor:backgroundColor];
}
}

@end
  1. Define a QRCellLabel class that mirrors common UILabel properties for convenient use. At compile time, forbid direct calls to setBackgroundColor: and expose a custom qr_setBackgroundColor: method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@interface QRCellLabel : UIView

@property(nullable, nonatomic,copy) NSString *text;
@property(null_resettable, nonatomic,strong) UIFont *font;
@property(null_resettable, nonatomic,strong) UIColor *textColor;
@property(nonatomic,assign) NSTextAlignment textAlignment;
@property(nonatomic,assign) NSLineBreakMode lineBreakMode;

// Notice NS_UNAVAILABLE: direct calls are forbidden at compile time.
- (void)setBackgroundColor:(UIColor *_Nullable)backgroundColor NS_UNAVAILABLE;

// Expose our own background-color setter.
- (void)qr_setBackgroundColor:(UIColor *_Nullable)backgroundColor;

// Add more properties below if needed, then implement setters in the .m file.
@end
  1. QRCellLabel contains two subviews: a UIImageView and a QRCellInnerLabel. 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 on shouldSetBackgroundColor, set QRCellInnerLabel’s background color, then immediately turn shouldSetBackgroundColor off. This way the control’s background color can only be changed through the method it exposes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@implementation QRCellLabel
{
UIImageView* _bgView;
QRCellInnerLabel* _label;
}

- (void)setupBackground
{
_bgView = [[UIImageView alloc]init];
_bgView.backgroundColor = [UIColor clearColor];
[self addSubview:_bgView];
}

- (void)setBackgroundColor:(UIColor *)backgroundColor
{
// Do nothing. This avoids external background-color changes.
}


- (void)qr_setBackgroundColor:(UIColor *)backgroundColor
{
[_bgView setImage:[UIImage qr_imageWithColor:backgroundColor]];

_label.shouldSetBackgroundColor = YES;
_label.backgroundColor = UIColor.clearColor;
_label.shouldSetBackgroundColor = NO;
}

// Override common setters.

- (void)setFont:(UIFont *)font{
_label.font = font;
}

- (void)setText:(NSString *)text{
_label.text = text;
}

- (void)setLineBreakMode:(NSLineBreakMode)lineBreakMode{
_label.lineBreakMode = lineBreakMode;
}

- (void)setTextAlignment:(NSTextAlignment)textAlignment{
_label.textAlignment = textAlignment;
}

- (void)setTextColor:(UIColor *)textColor{
_label.textColor = textColor;
}

...

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.

  1. 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:

iOS Issue Notes: Lottie Pitfalls (figure 4)
1
2
3
4
5
6
7
8
9
10
11
12
_leftAnimationBundle = [NSBundle bundleWithURL:[NSBundle.mainBundle URLForResource:@"left_animation"  withExtension:@"bundle"]];
_leftAnimationView = [LOTAnimationView animationNamed:@"data" inBundle:self.leftAnimationBundle];
_leftAnimationView.frame = QRRectMake(24, 0, 80, 90);
_leftAnimationView.loopAnimation = NO;
[self addSubview:_leftAnimationView];


_rightAnimationBundle = [NSBundle bundleWithURL:[NSBundle.mainBundle URLForResource:@"right_animation" withExtension:@"bundle"]];
_rightAnimationView = [LOTAnimationView animationNamed:@"data" inBundle:self.rightAnimationBundle];
_rightAnimationView.frame = QRRectMake(100, 0, 80, 90);
_rightAnimationView.loopAnimation = NO;
[self addSubview:_rightAnimationView];

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// LOTComposition.m
+ (nullable instancetype)animationNamed:(nonnull NSString *)animationName inBundle:(nonnull NSBundle *)bundle {

// animationName is used as the key, and only the JSON file name is used.
NSArray *components = [animationName componentsSeparatedByString:@"."];
animationName = components.firstObject;

LOTComposition *comp = [[LOTAnimationCache sharedCache] animationForKey:animationName];
if (comp) {
return comp;
}

...

if (JSONObject && !error) {
LOTComposition *laScene = [[self alloc] initWithJSON:JSONObject withAssetBundle:bundle];
[[LOTAnimationCache sharedCache] addAnimation:laScene forKey:animationName];
laScene.cacheKey = animationName;
return laScene;
}
return nil;
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// LOTComposition.m
+ (nullable instancetype)animationNamed:(nonnull NSString *)animationName inBundle:(nonnull NSBundle *)bundle
{
NSArray *components = [animationName componentsSeparatedByString:@"."];

// Include the bundle as part of the key. Otherwise multiple bundles
// with the same internal JSON name can conflict.
NSString* animationKey = [NSString stringWithFormat:@"%@_%@",components.firstObject,bundle.bundlePath.lastPathComponent];

LOTComposition *comp = [[LOTAnimationCache sharedCache] animationForKey:animationKey];
if (comp) {
return comp;
}
...
if (JSONObject && !error) {
LOTComposition *laScene = [[self alloc] initWithJSON:JSONObject withAssetBundle:bundle];
[[LOTAnimationCache sharedCache] addAnimation:laScene forKey:animationKey];
laScene.cacheKey = animationKey;
return laScene;
}

return nil;
}
  1. 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
2
3
_leftAnimationView.loopAnimation = NO;// If set to YES, it keeps playing and no completion callback is triggered.
_leftAnimationView.completionBlock = [leftCompletionBlock copy];
[_leftAnimationView play];

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@weakify(self)
id (^leftCompletionBlock)(BOOL animationFinished) = ^(BOOL animationFinished)
{
@strongify(self)
if(self.leftAnimationView.tag == 0){
self.leftAnimationView.tag = 1;
[self.leftAnimationView play];
}
else{
self.leftAnimationView.tag = 0;
self.leftAnimationView.hidden = YES;

// Final callback handling.
...
}
};

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
2
3
4
5
6
7
8
// LOTAnimationView.m
- (void)_callCompletionIfNecessary:(BOOL)complete {
if (self.completionBlock) {
LOTAnimationCompletionBlock completion = self.completionBlock;
self.completionBlock = nil;
completion(complete);
}
}

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.

iOS Issue Notes: UIImageView Reuse (figure 5)

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
- (void)sd_cancelCurrentImageLoad 
{
[self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageLoad"];
}

- (void)sd_cancelImageLoadOperationWithKey:(NSString *)key {
// Cancel in progress downloader from queue
NSMutableDictionary *operationDictionary = [self operationDictionary];
id operations = [operationDictionary objectForKey:key];
if (operations) {
if ([operations isKindOfClass:[NSArray class]]) {
for (id <SDWebImageOperation> operation in operations) {
if (operation) {
[operation cancel];
}
}
} else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){
[(id<SDWebImageOperation>) operations cancel];
}
[operationDictionary removeObjectForKey:key];
}
}

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 UIImageView URL still matches the URL associated with the returned image data:
1
2
3
4
if([self.imageUrl isEqualToString:imageFetchItem.key])
{
self.image = image;
}

Summary

That is all for now. I will keep adding more notes later.

-------------本文结束 感谢您的阅读-------------
If this article helped you, your support encourages me to keep writing.

Title:iOS Issue Notes

Author:lingyun

Published:2018-11-13 22:45

Updated:2026-09-23 00:37

Original link:https://tsuijunxi.github.io/en/2018/11/13/ios-issue-notes/

License: Attribution-NonCommercial-NoDerivatives 4.0 International Please keep the original link and author when sharing.