IOS Fish weekly, mainly share the experience and lessons encountered in the development process, high-quality blog, high-quality learning materials, practical development tools, etc. The weekly warehouse is here: github.com/zhangferry/… If you have a good content recommendation, you can submit it through the way of issue. You can also apply to be our resident editor to maintain the weekly. Also can pay attention to the public number: iOS growth road, backstage click into the group communication, contact us, get more content.

The development of Tips

A few tips for Xcode’s time consuming statistics

Collect a few statistical tips for analyzing project time.

Collect statistics on the overall compilation time

On the command line, enter the following command:

$ defaults write com.apple.dt.Xcode ShowBuildOperationDuration -bool YES
Copy the code

After this step, you need to restart Xcode to take effect. After this step, you can see the time of the entire compilation phase in the Xcode status bar.

Critical phase time statistics

If this isn’t detailed enough, Xcode also provides a feature specifically designed to analyze the time spent in each phase.

Menu bar: Product > Perform Action > Build with Timing Summary

This step triggers compilation automatically, and time statistics are at the bottom of the compile log navigation.

It also corresponds to an Xcodebuild parameter, showBuildTimingSummary, with which the build log also carries a statistical analysis of the elapsed time of each phase.

Swift time threshold

The Swift compiler provides the following two parameters:

  • -Xfrontend -warn-long-function-bodies=<millisecond>
  • -Xfrontend -warn-long-expression-type-checking=<millisecond>

The configuration positions are as follows:

Corresponding to long function body compile time warning and long type check time warning respectively.

Generally, enter 100, indicating that a warning will be provided if the time of the type exceeds 100ms.

Include of non-modular header inside framework module

When a component is frameworkalized, this problem is triggered if another unframeworkalized component (the.a static library) is introduced in the public header file. The error log indicates that the Framework contains non-modular header files, which means that if we’re going to do it, all of its dependencies should be modular, so it should be a step-by-step process from the bottom library to the top. If the underlying dependency cannot be easily modified, there are other ways to get around the compile error.

Search for non-modular In Build Settings and set the Allow non-modular Includes In Framework Modules option to Yes.

This option works for OC module code, but for Swift references you need to add another compiler parameter: -xcc-wno-error =non-modular-include-in-framework-module. Add location:

Note that both Settings are for projects, not component libraries. In addition, these are all temporary solutions, so it’s better to make all dependent libraries fully modular.

The Bug

IOS 14.5 UDP broadcast sendto returns -1

Edited by FBY Zhan Fei

1. Background

  1. After the mobile phone system is upgraded to iOS 14.5, UDP broadcast fails to be sent
  2. Older versions of the project used sockets
  3. The new version of the project uses CocoaAsyncSocket
  4. Both UDP packet sending modes report an error No route to host

The details of the error report are as follows:

sendto: -1
client: sendto fail, but just ignore it
: No route to host
Copy the code

2. Problem analysis

2.1 Sendto Return -1 Troubleshooting

We know that sending a broadcast sendto returns -1, normally sendto returns a value greater than 0. First check whether the socket connection is established

self._sck_fd4 = socket(AF_INET,SOCK_DGRAM,0);
if (DEBUG_ON) {
     NSLog(@"client init() _sck_fd4=%d".self._sck_fd4);
}
Copy the code

Self. _sck_fd4 print:

server init(): _sck_fd4=12
Copy the code

The socket connection is normal, then determine the data packet sending

sendto(self._sck_fd4, bytes, dataLen, 0, (struct sockaddr*)&target_addr, addr_len) = - 1
Copy the code

Data sending failure

2.2 increase NSLocalNetworkUsageDescription permissions
  1. Info. Add NSLocalNetworkUsageDescription plist

  2. Send a UDP broadcast, trigger permission dialog box, let the user click ok, allow access to the local network.

Found that the problem was still there

2.3 Checking unicast Sending

In the project, the hostName setting for transmitting broadcasts is 255.255.255.255. To check whether unicast messages can be sent successfully, determine whether unicast messages can be sent first.

If you change the unicast address to 192.168.0.101, you can send unicast messages successfully. If you change the unicast address to 192.168.0.101, you can send unicast messages successfully in CocoaAsyncSocket library.

192.168.0.255 is recommended for UDP broadcast. After changing the broadcast address, the device can receive UDP broadcast data.

Problem solving

Because 192.168.0.255 is only the current local address, App needs to dynamically change the first three segments 192.168.0 local address. The solution is as follows:

NSString *localInetAddr4 = [ESP_NetUtil getLocalIPv4];
NSArray *arr = [localInetAddr4 componentsSeparatedByString:@ "."];
NSString *deviceAddress4 = [NSString stringWithFormat:@ "% @. % @. % @. 255",arr[0], arr[1], arr[2]].Copy the code

When sending packet filtering, you only need to filter whether the last segment of the address is 255

bool isBroadcast = [targetHostName hasSuffix:@ "255"];
Copy the code

Reference: Resolve iOS 14.5 UDP broadcast sendto return -1 – show fei

Programming concepts

Shi da haiteng, zhangferry

This is the second installment of the core knowledge you need to know about the program, and you can download the full article.

What is binary

The computer is composed of IC electronic components, among which CPU and memory are also a kind of IC electronic components. The IC is composed of pins, and all the pins have only two voltages: 0V and 5V. This characteristic determines that the information processing of the computer can only be represented by 0 and 1, that is, binary processing. Binary consists of several important concepts, which are briefly introduced here:

complement

If a signed integer is represented by 8 bits, the highest bit is the sign bit, and 1 is 0000 0001. So what is minus 1? The answer is: 1111, 1111. If you see this notation for the first time, it might be a little bit strange, but it’s not 1000, 0001, but it’s a deduction based on addition. We use the computer to calculate 1-1, that is, 1 + (-1), that is, 0000 0001 + 1111 1111, and the result is 1 0000 0000, ignoring the high 1 of the overflow, and the result is 0. So minus 1 corresponds to binary 1111, 1111. The representation of positive numbers to negative numbers gives rise to the concept of complement, which is computed as follows:

So that’s how you compute from 1 to minus 1.

A shift

There are two kinds of shift, logical shift and arithmetic shift, see the following example:

A logical shift will fill in zeros in the void, and an arithmetic right shift will fill in sign bits in the void. If you move to the left, you’re adding zeros, no difference.

The symbols >> and << commonly used in code are arithmetic shifts, and some binary lookups use this technique because moving one bit to the right reduces the value by half.

What is big end and little end

There are two main types of data storage in computer hardware, big-endian and little-endian, and actually a middle-endian, which I won’t cover here because it’s used so rarely.

What’s the difference between the big end and the small end? Let’s do an example. For example, the 32-bit wide number 0x12345678 is stored in the small endian memory (assuming it is stored from address 0x4000) as follows:

Memory address 0x4000 0x4001 0x4002 0x4003
Store content 0x78 0x56 0x34 0x12

In big-endian memory, the storage mode is:

Memory address 0x4000 0x4001 0x4002 0x4003
Store content 0x12 0x34 0x56 0x78

The difference is that at low bytes, the small-endian mode stores the low bits, while the big-endian mode stores the high bits. Because we tend to look at the high first and then the low, the big end is more intuitive; But it is more efficient for the processor to process the data in the low order first. That’s why there are big end and small end models.

The small end mode, which is currently used by iOS and macOS applications, can be verified by:

if (NSHostByteOrder() = =NS_BigEndian) {
     NSLog(@"BigEndian");
} else if (NSHostByteOrder() = =NS_LittleEndian) {
     NSLog(@"LittleEndian");
}
Copy the code

What is caching

The interior of memory is composed of various IC circuits. There are many kinds of memory, but it is mainly divided into three kinds of memory: random access memory (RAM), read-only memory (ROM) and Cache. The Cache is usually divided into L1 Cache (L1 Cache), L2 Cache (L2 Cache), and L3 Cache (L3 Cache). It is located between the memory and the CPU. It is a memory with faster read and write speed than the memory. These categories are getting faster and faster from front to back.

Why are there so many caches? There are two main considerations: speed and cost. The higher the read speed, the higher the equipment cost, and the caches were added to balance the two. The latter can be used as the cache of the former, for example, main memory can be used as the cache of the hard disk, or the cache can be used as the cache of main memory.

Here is a comparison of read speeds for various devices:

The logic of the cache is that if there is no corresponding data, it will look up one level. If it finds the same data, it will cache it at the same level. The next time it looks for the same content, it can call it directly from the cache of the same level. Because the capacity of the cached part is generally smaller than that of its upper level, the cached content cannot always exist and needs to be removed according to certain rules, which leads to the LRU (Least Recently Used) algorithm, which weeded out the Least accessed data from the cache in a recent period of time. Improve cache utilization.

Credit: bowdoin.edu lec18.pdf

What is a compression algorithm

A compaction algorithm is an algorithm that compacts data. It consists of two steps: compaction and uncompaction. In fact, it is an algorithm that reduces the file byte space and occupies space without changing the original file attributes.

According to the definition of compression algorithm, we can divide it into different types:

Lossy and lossless

Lossless compression: it can reconstruct the compressed data without distortion and restore the original data accurately. It can be used to compress executable files, common files, disks, and multimedia data when data accuracy is strictly required. The compression of this method is small. Such as difference coding, RLE, Huffman coding, LZW coding, arithmetic coding.

Lossy compression: there is distortion, the original data can not be completely accurate recovery, the reconstructed data is only an approximation of the original data. It can be used in situations where the accuracy of data is not high, such as multimedia data compression. The compression of this method is relatively large. Examples are predictive coding, sound sensing coding, fractal compression, wavelet compression, JPEG/MPEG.

symmetry

If the complexity of the codec algorithm and the required time are about the same, it is a symmetric coding method, and most compression algorithms are symmetric. However, there are also asymmetries, which are generally difficult to encode and easy to decode, such as Huffman coding and fractal coding. But the encoding method used in cryptography is the opposite. It is easy to encode and very difficult to decode.

Between frames and within frames

In video coding, in-frame and inter-frame encoding methods are used at the same time. In-frame encoding refers to the encoding method completed independently in a frame of image, and static image encoding, such as JPEG; Interframe coding, on the other hand, requires reference to the before and after frames to encode and decode, and takes into account the compression of time redundancy between frames in the encoding process, such as MPEG.

RLE coding

RLE (run-length encoding) is a lossless encoding algorithm that counts the number of encoded characters. For example, A data string “AAAABBBCCDEEEE”, consisting of 4A’s, 3B’s, 2C’s, 1D’s and 4E’s, can be compressed into 4A3B2C1D4E by RLE (from 14 units to 10 units).

Haverman coding

Huffman coding is a lossless compression coding method that uses variable-length coding tables to encode source symbols. It is characterized by the use of shorter coding symbols for characters that occur more frequently. The result of Huffman encoding AAAAAABBCDDEEEEEF is as follows:

Good blog

Edit: King Pilaf is here

1, the growth path of ordinary technical people – a client veteran’s experience — from the public number: old driver Weekly

Don’t forget to be a scholar. I agree with some of them. I don’t know if you are like me, there are all kinds of anxiety: customer three elimination, internal volume, 35 years old crisis… Take time to read this article, so that the heart of anxiety to get temporary relief.

2, Swift Compilation (A) Protocol Witness Table preliminary study — from the public account: Swift community

I have paid attention to Protocol Witness Table before, but I did not take the time to understand it. A very deep article, worth reading, if there is time to follow the author’s train of thought hands-on debugging.

Wakeup in XNU — from the public account: Netease Cloud music big front end team

At the end of last year, I helped a classmate parse a wakeup log in the group. The wakeup log may seem strange, but many students may not have similar problems. This professional article can give you a preliminary understanding of Wakeup.

4. Kuaishou client stability system construction — from CSDN: Kuaishou technical team

In this, it is mentioned that The fast hand encountered wakeup crash and how to locate the related problems.

5, iOS skills development first understanding symbols and links — from nuggets: I am a good baby

Familiarity with Mach-O and links will be a plus if you are interviewing.

6. Understand and analyze iOS Crash — from SegmentFault: Tencent WeTest

IOS Crash related to a very good and comprehensive article, the author added annotations to help us understand, has been collected.

7. Swift practice of A station — Part TWO — from the public account: Kuaishou Big front-end technology

This is the second part of Swift practice by Mr. Daiming. Compared with the previous part, it is more about macro introduction of Swift, and this part is closer to the actual development scene. There are two important problems to be solved in the promotion of Swift actual combat. One is modulealization, which deals with components and mixed programming, and the other is Swift Hook scheme, which deals with various Hook scenarios.

Learning materials

Mimosa

Swift by Sundell

Address: www.swiftbysundell.com/

John Sundell’s blog (he is also the author of Publish) features articles, podcasts and news about Swift development. The articles are clear and easy to read, and have a wide range of difficulty, so developers at all levels should be able to find articles that are appropriate for their level. Some of the SwiftUI articles on its website also provide a real-time preview of how the SwiftUI code works, which is very comfortable 😈.

100 Days of SwiftUI from Paul Hudson

Address: www.hackingwithswift.com/100/swiftui

Paul Hudson is a free SwiftUI course, relatively basic, is an excellent beginner’s tutorial. He will briefly teach Swift and then start building iOS apps using SwiftUI. There are plenty of basic tutorials and solutions for iOS development on the website Hacking with Swift, which is generally suitable for those new to iOS development: 🤠.

Tools recommended

Brave723

SwiftFormat for Xcode

Address: github.com/nicklockwoo…

Software status: Free, open source

Used to introduce

SwiftFormat is a command line tool for reformatting Swift code. It formats the code while keeping the meaning of the code

Many projects have a fixed code style, and a common code specification helps to iterate and maintain the project, while some programmers ignore these rules. At the same time, manually forcing code style changes is error-prone, and no one wants to do the boring work.

If there were an automated tool that could do this, it would be almost perfect. When reviewing code, you don’t need to emphasize the tedious formatting every time.

Notion

Address: www.notion.so/desktop

Software status: Individual free, team charge

Used to introduce

Notion is a very good personal notes software, it will be “all things” of thinking used in notes, let users can create powerful and unconstrained style, drag and drop, links; Notion is not only a great personal note-taking software, it also has project management, wikis, documentation, and more.

The core function
  • Supports the import of rich files and content
  • Built-in rich templates
  • Simple user interface, convenient drag and new operation
  • Support for Board views, while you can add any number of other types of views and customize related filtering criteria
  • Copy the image to complete the upload, no need for other map bed
  • Save historical operation records and record relevant time
  • Powerful association functions, such as calendar and notes, notes and files, and web links

Contact us

IOS Fishing Weekly Issue 7

IOS Fishing Weekly Issue 8

IOS Fishing Weekly Issue 9

IOS Fishing Weekly issue 10

IOS Fishing Weekly eleventh issue