This profile

  • Tips: Some introduction to low battery mode.
  • Interview module: Objective-C message mechanism (part 2).
  • Good blog: Organized several Swift Tips articles.
  • Resources: Gitmoji: a GitHub Emoji guide to submitting messages 😎
  • Development tools: Tools that can use Swift to develop Android apps: SCADE; Visual parsing.ndjsonTools for files: privacy-Insight.

This topic

@Zhangferry: This interview is a separate piece, you can check the next post of this public account, or visit this link people interview – Microsoft Offer Road

This week touched fish ushered in a new partner: Dongpo elbow son. Elbow zi had been trained for a period of time due to physical reasons, and also needed to make health records due to physical reasons. However, I did not find a satisfactory way to record, so I decided to develop my own development, from which I formed a bond with iOS and started independent development. There will be another interview with him to learn more about his story, and you can also follow him on his blog: Elbow’s Swift Notepad www.fatbobman.com/.

The development of Tips

Summer

Low power mode

Starting with iOS 9, Apple added a Low Power Mode to the iPhone. Users can go to Settings -> Battery to enable low battery mode. In low power mode, iOS extends battery life by enacting certain energy saving measures, including, but not limited to, the following:

  • The CPU and GPU performance is reduced, and the screen refresh rate is reduced
  • Active or background activities, including networking, will be suspended
  • Reduce screen brightness
  • Reduce the automatic lock time of the device
  • Email cannot be automatically retrieved, dynamic effects such as gyroscope and compass will be weakened, and dynamic screensavers will be disabled
  • For 5G-enabled iPhone devices, the 5G capabilities will be limited, unless you’re watching streaming

Will the above energy saving measures affect your application, and if so, you may need to take appropriate measures for low power modes.

lowPowerModeEnabled

We can use NSProcessInfo to get the process information we want. This thread-safe singleton class provides developers with a variety of information about the current process.

One notable point is that NSProcessInfo will attempt to interpret environment variables and command-line arguments as Unicode, returned as utF-8 strings. If the process fails to convert to Unicode or a subsequent C string conversion fails — the process is ignored.

Of course, we still need to pay attention to the low power mode flag, a Boolean value that indicates whether the device has lowPowerModeEnabled — lowPowerModeEnabled.

if NSProcessInfo.processInfo().lowPowerModeEnabled {
    // The current user is in low power mode
} else {
    // The current user is not in low power mode
}
Copy the code

NSProcessInfoPowerStateDidChangeNotification

In order to better respond to power mode switch, when the battery to 80% would pull out of the low power mode, Apple provides us with a global NSProcessInfoPowerStateDidChangeNotification notice.

NSNotificationCenter.defaultCenter().addObserver(
    self,
    selector: "yourMethodName:",
    name: NSProcessInfoPowerStateDidChangeNotification,
    object: nil
)

func yourMethodName:(note:NSNotification) {  
    if (NSProcessInfo.processInfo().isLowPowerModeEnabled) {  
      // The current user is in low power mode
      // Here reduce animation, lower frame rate, stop position updates, disable synchronization and backup, etc
    } else {  
      // The current user is not in low power mode
      // Resume prohibited operations here}}Copy the code

conclusion

Make changes to the overall energy efficiency and user experience of the platform by following the recommendations of the iOS Application Energy Efficiency Guide.

reference

  • Enabling low battery mode on an iPhone will lose 15 features
  • IOS Application Energy Efficiency Guide
  • Low battery mode in response to iPhone devices
  • WWDC 2015 Session 707 Achieving All-day Battery Life

Parsing the interview

Edit: Xiao Haiteng of Normal University

Objective-c messaging (part 2) In the last issue we discussed the first phase of the objc_msgSend execution process message sending, so in this issue we will discuss the next two phases of dynamic method parsing and message forwarding.

Dynamic method parsing

If the message sending phase fails to process the unknown message, a dynamic method resolution is performed. We can implement this in this phase by adding methods dynamically to handle unknown messages. After the dynamic method is resolved, the message is sent again, starting from the “Find IMP in the receiverClass method cache” step.

Specifically, during this phase, Runtime calls the following methods based on the receiverClass type being class/meta-class:

+ (BOOL)resolveInstanceMethod:(SEL)sel;
+ (BOOL)resolveClassMethod:(SEL)sel;
Copy the code

We can override the above method and dynamically add methods using the class_addMethod function. One thing to note is that instance methods are stored in class objects, and class methods are stored in metaclass objects, so be careful about passing parameters here.

BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
Copy the code

If we handle the unknown message correctly in this phase, then we can find IMP and call it when we enter the message sending phase again, otherwise we will enter the message forwarding phase.

forward

Message forwarding is divided into Fast and Normal stages. As the name implies, Fast is faster.

  1. Fast: Find an alternate receiver and try to forward the unknown message to the alternate receiver for processing.

Specifically, you send the following message to the receiver, noting that there are class methods and instance methods.

(+ / -id)forwordingTargetForSelector:(SEL)selector;
Copy the code

If we override the above method and return one correctly! The Runtime sends the current unknown message to the standby receiver via objc_msgSend to start the new message execution process.

If the phase still fails to process the unknown message, Normal is entered. Note that the contents of unknown messages cannot be modified during the Fast phase. If necessary, you can modify the contents during the Normal phase.

  1. Normal: Starts full message forwarding, encapsulates all the details of the message in an NSInvocation instance, and gives the receiver one last chance to handle the unknown message.

Specifically, the Runtime first gets the method signature for the unknown message by calling the following methods.

(+ / -NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector;
Copy the code

Then, based on this method signature, create a NSInvocation instance that encapsulates the entire contents of the unknown message (Target, Selector, arguments), then call the following method and pass in the NSInvocation instance as a parameter.

(+ / -void)forwardInvocation:(NSInvocation *)invocation;
Copy the code

We can override the above method to handle unknown messages. In the forwardInvocation: method, we can direct the unknown message to another object (too expensive to handle in Fast), change the unknown message to another object, or even define any logic.

If Normal or failed to deal with the unknown news, if there is no return to the method signature, then will call doesNotRecognizeSelector:; If the forwardInvocation is not overwritten, NSObject’s forwardInvocation is called: The default implementation, and the default implementation of this method is also called doesNotRecognizeSelector:, show that unknown message eventually failed to be processed, all the process ends with a Crash program objc_msgSend.

Some caveats

  • When overriding the above method, the unknown messages handled by this class should not be handled by the parent class. Instead, the implementation of the parent class should be called, so that every class in the inheritance hierarchy has a chance to handle the unknown messages, up to NSObject.
  • Each of these phases has an opportunity to process messages, but the earlier the message is processed, the better the performance.
    • In the bestDynamic method parsingPhase is completed so that the Runtime can cache the method so that the object does not need to be started later when it receives the same messageDynamic method parsing 与 forwardProcess.
    • If theforwardThe phase simply wants to forward the message to the alternate receiver, which is best done in the Fast phase. Otherwise you have to create and handle the NSInvocation instance.
  • respondsToSelector:Will triggerDynamic method parsing, but it will not triggerforward.

Good blog

I am Xiong Da, Dongpo Elbow son

1. [iOS] Swift Tips – (1) — From Nuggets: Layer

The article is the author’s study notes. The author compiled objccn. IO/into 6 articles, suitable for reading on the subway. In this article, we mainly introduce the writing methods and uses of Currization, multivariate groups, operators and so on.

10 Tips to Be a Better Swift Engineer

King Piraf: Learning Swift is not only about being able to write Swift code, but also about being able to use Swift gracefully, which is the purpose of this blog theme. This article introduces the clever use of extensions, generics, computing properties and other optimization code, is more interesting for beginners.

3. Write better Swift code: Tips gap-nuggets from OldBirds

@Dongpocuzi: The author introduced several practical Swift using skills in the article, including avoiding naming conflicts through prefixes, quick exchange of values, @discardableresult, access control, etc., which are very helpful for daily development.

4, Swift: Where keyword use — from nuggets: season_zhu

This article introduces several scenarios in which WHERE is used in Swift, including generic constraints, specified types, etc., in addition to the for loop. This helps to better understand where usage in different contexts.

5. Swift – Use Color Literal to realize intelligent hint of Color in code (Xcode comes with its own function) — from sailing song

Color Literal allows Color assignment to be visible.

Use Swift custom operator overloading — from nuggets: Shankss

I am xiong Da: Ever think of “+”, “-“, “??” How is it implemented at the bottom? Do you want to implement a special operator yourself, such as: “–>”, this article takes you to explore.

Learning materials

Mimosa

gitmoji

Address: gitmoji.js.org/

Gitmoji is a GitHub emoji guide for submitting messages 😎, dedicated to becoming a standardized emoji cheat sheet πŸ“‹. When you submit messages, using emoji descriptions becomes an easy way to identify the purpose and intent of the submission 🍰, Because maintainers only need to look at the emoji used to understand 🧐. Because there are so many emojis out there, a guide was created to make using emojis easy, understandable, and consistent πŸ₯³.

Tools recommended

CoderStar, Zhangferry

SCADE

Address: www.scade.io/

State of the software

  • SCADE Community: Free
  • SCADE Professional: $29 per month/user

Software Introduction:

With SCADE we can use Swift language for cross-end native development. Its description features are as follows:

  • Cross-platform: Develop for iOS and Android using the same source code
  • Native features: Unrestricted access to all iOS and Android features
  • Unmatched speed: Swift is compiled to native binaries for unmatched application performance
  • Swift Framework: Use popular Swift frameworks such as Swift Foundation on iOS and Android without code changes
  • .

Privacy-Insight

Address: github.com/Co2333/Priv…

Software status: Free, open source

Software Introduction:

Parse the system privacy report in the format of. Ndjson in iOS 15, using SwiftUI.

Privacy log generation Settings -> Privacy -> Open record App activity, wait for a period of time click the store App activity button below, you can collect this period of privacy log. The storage will generate a.ndjson file, which can be exported using privacy-Insight.

The following is my 1-day privacy request record:

Both wechat and Toutiao have a very high frequency of obtaining privacy rights. I am sure THAT I did not access albums through wechat so frequently. The issue of wechat’s frequent access to photo albums has also been hotly discussed recently. It is hoped that not only wechat, but also all mainstream apps should pay attention to user privacy issues.

As a relatively effective privacy protection scheme for users, close the “background refresh” of the corresponding App, turn off bluetooth, location and other permissions if it is not necessary, and change the calling permission of album to “selected photos”.

About us

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.

Phase to recommend

IOS Fishing Weekly 28th issue

IOS Fishing Weekly issue 27

IOS Fishing Weekly Issue 26

IOS Fishing Weekly 25th issue