NSProcessInfo is a class we must use to count the startup time of our APP. Let’s learn about it from the official documentation.
The content of NSProcesshidp is basically not too difficult to navigate quickly.
NSProcessInfo
NSProcessInfo is a system process information object that contains methods that allow you to set or retrieve various types of information about a running application (that is, a process).
A collection of information about the current process.
Overview
Each process has a shared NSProcessInfo object called the process information broker (NSProcessInfo *info = [NSProcessInfo processInfo];) .
The process broker can return arguments (char * argv[]), environment variables, hostName, and process name. The processInfo class method (or class attribute) returns the shared proxy of the current process (that is, an NSProcessInfo object that represents our current program, either in the current process or anywhere in our current program, via this class attribute), the process whose object sent the message. For example, the following line returns the NSProcessInfo object and then provides the name of the current process:
NSString *processName = [[NSProcessInfo processInfo] processName];
// print :(name of current project)🤯 🤯 🤯 Test_ipa_simpleCopy the code
Note NSProcessInfo is thread-safe on macOS 10.7 and later. (You should realize that not all of the properties and methods of the NSProcessInfo object are read-only, and there are some that you can set. [NSProcessInfo processInfo] can be used anywhere in our project to retrieve the current process information object.
The NSProcessInfo class also includes the operatingSystem method, which returns an enumeration constant identifying the operatingSystem on which the process is executing.
If the NSProcessInfo object cannot convert environment variables and command-line arguments to Unicode as UTF-8 strings, They try to interpret environment variables and command-line arguments in the user’s default C string encoding. If neither Unicode nor C string conversions work, the NSProcessInfo object ignores these values.
Managing Activities
For the benefit of the user, the system has heuristics to improve the application’s battery life, performance, and responsiveness. You can use the following methods to manage or alert the system to Activities that your application has special requirements for:
beginActivityWithOptions:reason:
endActivity:
performActivityWithOptions:reason:usingBlock:
In response to creating an activity, the system disables some or all of the heuristics so that your application can complete quickly, while still providing responsive behavior when the user needs it.
You can use Activities when your application performs long-running operations. Use this API if the activity might take different times (for example, calculating the next step in a chess game). This ensures correct behavior in the event of changes in the amount of data or the functionality of the user’s computer. You should group your activities into one of two main categories:
- User-initiated: These are limited length activities explicitly started by the user. For example, export or download a file specified by the user.
- Background tasks: These are finite-length activities that are part of the normal operation of the application, but are not explicitly initiated by the user. For example, automatic saving, indexing, and automatic downloading of files.
In addition, if your application requires a high-priority I/O, you can include NSActivityLatencyCritical logo (using the bitwise OR). You should only use this flag for activities such as audio or video recording that really require high priority.
You do not need to use this API if your activities occur simultaneously in event callbacks on the main thread.
Please note that failure to end these activities for an extended period of time can have a significant negative impact on the performance of the user’s computer, so be sure to use only the minimum time required. Preferences may override the requests of your application.
You can also use this API to control automatic termination or sudden termination (see Sudden termination). Such as:
id activity = [[NSProcessInfo processInfo] beginActivityWithOptions:NSActivityAutomaticTerminationDisabled reason:@"Good Reason"];
// Perform some work
[[NSProcessInfo processInfo] endActivity:activity];
Copy the code
Is equivalent to:
[[NSProcessInfo processInfo] disableAutomaticTermination:@"Good Reason"];
// Perform some work
[[NSProcessInfo processInfo] enableAutomaticTermination:@"Good Reason"];
Copy the code
Because this API returns an object, it may be easier to start and end pairing than using the auto-terminate API — if the object is released before endActivity: is called, the activity automatically ends.
The API also provides a mechanism to disable system-wide idle sleep and display idle sleep. These can have a big impact on the user experience, so be sure to end activities that disable sleep (including NSActivityUserInitiated).
Sudden Termination
MacOS 10.6 and later includes a mechanism that allows the system to log out or close applications more quickly by terminating them when possible, rather than asking them to exit on their own.
Your application can enable this feature on a global basis and then manually override its availability during allowing sudden termination of operations that could result in data corruption or poor user experience. Alternatively, your application can manually enable and disable this feature.
The methods enablesuddenterOutline and DisablesuddenterOutline respectively reduce or increase a counter that had a value of 1 when the process was first created. When the value of the counter is 0, the application is considered safe to terminate and can be terminated by the system without first sending any notification or event to the process.
By adding a key to your application’s info.plist, your application can support abrupt termination at startup. If the Info in NSSupportsSuddenTermination plist key and its value to YES, is equivalent to calling enableSuddenTermination during application startup. This allows the application process to terminate immediately. You can still override this behavior by calling disablesuddenterOutline.
In general, you can disable abrupt termination when the application delays work that must be done before the application terminates. For example, if an application is delaying writing data to disk and abrupt termination is enabled, put the sensitive action together with the DisablesuddenterOutline call, perform the necessary action, and then send an Enablesuddenteroutline message for balancing.
In a proxy or daemon executable that doesn’t rely on AppKit, you can immediately and manually call enablesuddEnteroutline. Then, you can use the Enable and disable methods whenever the process has work that must be done before it terminates.
Some AppKit features automatically disable Sudden termination temporarily to ensure data integrity.
-
NSUserDefaults temporarily disables Sudden termination to prevent the process from being terminated when a default value is set and a preference file containing that default value is written to disk.
-
NSDocument temporarily disables Sudden termination to prevent the process from being terminated when the user makes changes to the document and writes the user changes to disk.
Note You can use the LLDB command to determine the value of sudden termination. Print (long) [[NSClassFromString (@ “NSProcessInfo”) processInfo] _suddenTerminationDisablingCount] don’t try to call or rewritten in the application SuddenTerminationDisablingCount method (private). It exists only for debugging purposes and can disappear at any time.
Thermal State and App Performance in macOS
Thermal State and application performance in macOS.
In macOS, the current thermal state is used to determine whether an application should reduce system usage. The macOS 10.10.3 and higher versions, you can register NSProcessInfoThermalStateDidChangeNotification, so that it is notified in hot state changes. Using a thermalState (@ property (readonly) NSProcessInfoThermalState thermalState;) Example Query the current status. Your application should reduce the use of the system under Higher Thermal States. Concerning the operation of the proposal, please refer to the NSProcessInfoThermalState.
Topics
Getting the Process Information Agent
processInfo
@property (class, readonly, strong) NSProcessInfo *processInfo; Returns the process information broker for the current process (shared process information broker for the process). , which is a class property that we can call directly using NSProcessInfo.
An NSProcessInfo object is created the first time this method is called, and the same object is returned each subsequent call.
Accessing Process Information
arguments
@property (readonly, copy) NSArray
*arguments; An array of strings containing the process’s command-line arguments. This array contains all the information passed in the argv array, the argument to main, whose first element is the current executable file name. The following example code is printed:
int main(int argc, char * argv[]) {
NSString * appDelegateClassName;
NSLog(@"🦁 🦁 🦁 % s", __func__);
NSProcessInfo *info = [NSProcessInfo processInfo];
NSLog(@"🤯 🤯 🤯 % @", info.arguments);
printf("🤯 🤯 🤯 arg c: % d \ n", argc);
printf("🤯 🤯 🤯 % s \ n", argv[0]);
@autoreleasepool {
// Setup code that might create autoreleased objects goes here.
appDelegateClassName = NSStringFromClass([AppDelegate class]);
}
return UIApplicationMain(argc, argv, nil, appDelegateClassName);
}
// Console output:
202107 -- 15 22:27:35.041884+0800 Test_ipa_simple[14236:1094002] 🦁 🦁 🦁 main202107 -- 15 22:27:35.042078+0800 Test_ipa_simple[14236:1094002] 🤯 🤯 🤯 ("/Users/hmc/Library/Developer/CoreSimulator/Devices/CC2922E4-A2DB-43DF-8B6F-D2987F683525/data/Containers/Bundle/Applicat ion/67BEBCD2-E89F-4742-B3B0-1827F0E98BD8/Test_ipa_simple.app/Test_ipa_simple") 🤯 🤯 🤯 arg c:1🤯 🤯 🤯 / Users/HMC/Library/Developer/CoreSimulator/Devices/CC2922E4 - A2DB43 -DF-8B6F-D2987F683525/data/Containers/Bundle/Application/67BEBCD2-E89F- 4742.-B3B0-1827F0E98BD8/Test_ipa_simple.app/Test_ipa_simple
Copy the code
We can also use the Edit Scheme… -> Run -> Arguments -> Arguments Passed On Launch {“name”:”iOS”,”arme”:” arguments “}, then we print [NSProcessInfo processInfo]. Arguments to print as follows:
202107 -- 15 22:33:01.141910+0800 Test_ipa_simple[14299:1099660] 🤯 🤯 🤯 ("/Users/hmc/Library/Developer/CoreSimulator/Devices/CC2922E4-A2DB-43DF-8B6F-D2987F683525/data/Containers/Bundle/Applicat ion/6CC75292-B479-4FC0-A5B1-A21C11BEF2D5/Test_ipa_simple.app/Test_ipa_simple"."{name:iOS,arme:\U53c2\U6570}"
)
Copy the code
environment
@property (readonly, copy) NSDictionary
*environment;
The variable name (key) and its value in the environment in which the process is started. (Too much to post directly here.)
globallyUniqueString
@property (readonly, copy) NSString *globallyUniqueString;
Globally unique identifier of the process.
The global ID of a process includes the host name, process ID, and timestamp, which ensures that the ID is unique to the network. This property generates a new string each time its getter is called and uses counters to ensure that strings created from the same process are unique.
macCatalystApp
@interface NSProcessInfo (NSProcessInfoPlatform)
@property (readonly, getter=isMacCatalystApp) BOOL macCatalystApp API_AVAILABLE(macos(10.15), ios(13.0), watchos(6.0), tvos(13.0));
@property (readonly, getter=isiOSAppOnMac) BOOL iOSAppOnMac API_AVAILABLE(macos(11.0), ios(14.0), watchos(7.0), tvos(14.0));
@end
Copy the code
A Boolean value indicating whether the process originated from an iOS application and is running on macOS.
When the value of this property is YES, the process:
- use
Mac Catalyst
To build theMac
Apps, or running on Apple SiliconiOS
Applications. - in
Mac
To run on.
Frameworks supporting iOS and macOS use this property to determine if a process is a Mac application built using MacCatalyst. To conditionally compile source code that runs only in macOS, use #if TARGET_OS_MACCATALYST instead.
Note To distinguish between iOS applications running on Apple Silicon and Mac applications built using Mac Catalyst, use the iOSAppOnMac property.
iOSAppOnMac
@interface NSProcessInfo (NSProcessInfoPlatform)
@property (readonly, getter=isMacCatalystApp) BOOL macCatalystApp API_AVAILABLE(macos(10.15), ios(13.0), watchos(6.0), tvos(13.0));
@property (readonly, getter=isiOSAppOnMac) BOOL iOSAppOnMac API_AVAILABLE(macos(11.0), ios(14.0), watchos(7.0), tvos(14.0));
@end
Copy the code
A Boolean value indicating that the process is an iPhone or iPad application running on a Mac.
The value of this property is YES only if the process is an iOS application running on a Mac. The value of this property is NO for all other applications on the Mac, including Mac applications built using Mac Catalyst. This property also does not apply to processes running on platforms other than macOS.
processIdentifier
@ property (readonly) int processIdentifier;
The process identifier (usually called the process ID).
processName
@ property (copy) nsstrings * processName;
Name of the process.
The process name is used to register application defaults and is used in error messages. It does not uniquely identify the process.
The Warning user default and other aspects of the environment may depend on the process name, so be very careful when changing it. Setting the process name in this way is not thread-safe.
Accessing User Information
Each user account in macOS has a full name (for example “Johnny Appleseed”) and an account name (for example “Jappleseed”). You can view these names from the Users and Groups panel in System Preferences, and you can log in to the Mac using any name.
userName
@interface NSProcessInfo (NSUserInformation)
@property (readonly, copy) NSString *userName API_AVAILABLE(macosx(10.12)) API_UNAVAILABLE(ios, watchos, tvos);
@property (readonly, copy) NSString *fullUserName API_AVAILABLE(macosx(10.12)) API_UNAVAILABLE(ios, watchos, tvos);
@end
Copy the code
Returns the account name of the current user. (Visible only on macOS)
fullUserName
@interface NSProcessInfo (NSUserInformation)
@property (readonly, copy) NSString *userName API_AVAILABLE(macosx(10.12)) API_UNAVAILABLE(ios, watchos, tvos);
@property (readonly, copy) NSString *fullUserName API_AVAILABLE(macosx(10.12)) API_UNAVAILABLE(ios, watchos, tvos);
@end
Copy the code
Returns the full name of the current user. (Visible only on macOS)
Sudden Application Termination
Disable or reenable the ability to be quickly killed. The default implementations of these methods increment or decrement, respectively, a counter whose value is 1 when the process is first created. When the counter’s value is 0 the application is considered to be safely killable and may be killed by the operating system without any notification or event being sent to the process first. If an application’s Info.plist has an NSSupportsSuddenTermination entry whose value is true then NSApplication invokes -enableSuddenTermination automatically during application launch, which typically renders the process killable right away. You can also manually invoke -enableSuddenTermination right away in, for example, agents or daemons that don’t depend on AppKit. After that, you can invoke these methods whenever the process has work it must do before it terminates. For example:
- NSUserDefaults uses these to prevent process killing between the time at which a default has been set and the time at which the preferences file including that default has been written to disk.
- NSDocument uses these to prevent process killing between the time at which the user has made a change to a document and the time at which the user’s change has been written to disk.
- You can use these whenever your application defers work that must be done before the application terminates. If for example your application ever defers writing something to disk, and it has an NSSupportsSuddenTermination entry in its Info.plist so as not to contribute to user-visible delays at logout or shutdown time, it must invoke -disableSuddenTermination when the writing is first deferred and -enableSuddenTermination after the writing is actually done.
Disables or re-enables the ability to be killed quickly. The default implementation of these methods increments or decays a counter, which has a value of 1 when the process is first created. When the counter has a value of 0, the application is considered safe to terminate and can be terminated by the operating system without first sending any notification or event to the process. If the application Info. Plist NSSupportsSuddenTermination entry has a value of true, Then NSApplication automatically calls the -EnablesSuddEnterOutline during application startup, which typically causes the process to terminate immediately. For example, you can also manually call -enablesumddenterOutline immediately ina proxy or daemon that doesn’t rely on AppKit. These methods can then be called as long as the process has work that must be done before it terminates.
NSUserDefaults
Use these to prevent the process from terminating between setting a default value and writing the preferences file that contains it to disk.NSDocument
Use these to prevent the process from terminating between the user making changes to the document and writing the user changes to disk.- These commands can be used when the application delays work that must be done before the application terminates. For example, if your application has delayed writing something to disk, and its
Info.plist
One of theNSSupportsSuddenTermination
The entry, so that it does not cause delays visible to the user on logout or shutdown, must be invoked on the first deferred write-disablesuddenternimination
And called after the write is actually done-enablesumddenternimination
.
This gives us the question “How do I exit an iOS app?” A: Writing an array is out of bounds. Here is another new way to exit iOS apps.
disableSuddenTermination
– (void) disablesuddEnterapi_available (MacOS (10.6)) API_UNAVAILABLE(ios, watchos, tVOs);
Disable applications that terminate quickly using sudden termination. (Visible only on macOS)
This method increments the Sudden termination counter. When the termination counter reaches 0, the application allows sudden termination.
By default, the Sudden termination counter is set to 1. This can be overridden in the application’s info.plist. For more information and debugging suggestions, see the Sudden Termination section above.
enableSuddenTermination
– (void) enablesuddEnterapi available (MacOS (10.6)) API_UNAVAILABLE(ios, watchos, tVOs); – (void) enablesuddEnterapi available (MacOS (10.6)) API_UNAVAILABLE(ios, watchos, tVOs);
Enable the application to kill quickly using sudden termination. (Visible only on macOS)
This method reduces the sudden termination counter. When the termination counter reaches 0, the application allows sudden termination.
By default, the Sudden termination counter is set to 1. This can be overridden in the application’s info.plist. For more information and debugging suggestions, see the Sudden Termination section above.
Controlling Automatic Termination
Increment or Decrement the counter tracking the number of automatic quit opt-out requests. When this counter is greater than zero, the app will be considered ‘active’ and ineligible for automatic termination. An example of using this would be disabling autoquitting when the user of an instant messaging application signs on, due to it requiring a background connection to be maintained even if the app is otherwise inactive. Each pair of calls should have a matching “reason” argument, which can be used to easily track why an application is or is not automatically terminable. A given reason can be used more than once at the same time (for example: two files are transferring over the network, each one disables automatic termination with the reason @”file transfer in progress”)
Increases or decreases the counter that tracks the number of automatic opt-out requests. When this counter is greater than zero, the application is considered “active” and does not qualify for automatic termination. An example of using this feature is to disable automatic logout when a user of an instant messaging application logs in, because the application needs to maintain a background connection even when it is inactive. DisableAutomaticTermination: and enableAutomaticTermination: every to call “reason there should be a matching parameters, it can be used to easily why tracking application may or may not be automatically terminated. A given reason can be used multiple times at the same time (e.g., two files are being transferred over the network, each with auto termination disabled for @”file Transfer in Progress “)
disableAutomaticTermination:
– (void) disableAutomaticTermination: (nsstrings *) a tiny API_AVAILABLE (macos (10.7)) API_UNAVAILABLE (ios, watchos tvos);
Disables automatic termination of applications. The reason parameter is the reason why automatic termination is disabled. (Visible only on macOS)
This method adds automatic termination counter. When the counter is greater than 0, the application is considered active and does not qualify for automatic termination. For example, you can disable automatic termination when a user of an instant messaging application logs in, because the application needs to remain connected in the background even when the application is inactive.
The Reason parameter is used to track why an application can or cannot terminate automatically, and can be checked by debugging tools. For example, if automatic termination is disabled before transferring files over the network, you can pass the string @”file Transfer in Progress “. After completion of the transmission using enableAutomaticTermination: restart automatically terminated, you should pass the matching string. A given reason can be used more than once; For example, if you transfer two files at the same time, you can disable automatic termination for each file and pass the same reason string.
enableAutomaticTermination:
– (void) enableAutomaticTermination: (nsstrings *) a tiny API_AVAILABLE (macos (10.7)) API_UNAVAILABLE (ios, watchos tvos);
Enable automatic termination of applications. The reason parameter is the reason for enabling automatic termination. (Visible only on macOS)
This method reduces automatic termination counter. When the counter is 0, the application can be terminated automatically.
The Reason parameter is used to track why an application can or cannot terminate automatically, and can be checked by debugging tools. For example, if automatic termination is disabled before transferring files over the network, you can pass the string @”file Transfer in Progress “. After completion of the transmission using enableAutomaticTermination: restart automatically terminated, you should pass the matching string. A given reason can be used more than once; For example, if you transfer two files at the same time, you can disable automatic termination for each file and pass the same reason string.
automaticTerminationSupportEnabled
Marks the calling app as supporting automatic termination. Without calling this or setting the equivalent info.plist key (NSSupportsAutomaticTermination), the above methods (disableAutomaticTermination:/enableAutomaticTermination:) have no effect, although the counter tracking automatic termination opt-outs is still kept up to date to ensure correctness if this is called later. Currently, passing NO has no effect. This should be called during -applicationDidFinishLaunching or earlier.
Setting it to YES marks the calling application as supporting automatic termination. Don’t call it or set of equivalent Info. Plist key (NSSupportsAutomaticTermination), the above method (disableAutomaticTermination: / enableAutomaticTermination:) is invalid, even though the counter tracking automatically terminate opt out still kept up to date in order to ensure correctness, if this is the call later. Currently, passing NO has NO effect. This should be called when – applicationDidFinishLaunching or earlier.
@ property BOOL automaticTerminationSupportEnabled API_AVAILABLE (macos (10.7)) API_UNAVAILABLE (ios, watchos tvos);
A Boolean value indicating whether the application supports automatic termination.
Don’t set this property or set of equivalent Info. The plist key (NSSupportsAutomaticTermination), the method disableAutomaticTermination: And enableAutomaticTermination: invalid, even though the counter tracking automatically terminate opt out still kept up to date in order to ensure the correctness of the call later. Currently, setting this property to NO does not work. This property should be in the application delegate applicationDidFinishLaunching: set before or earlier.
Getting Host Information
hostName
@property (readonly, copy) NSString *hostName;
Name of the host on which the process is being executed. For example my machine prints: ✳️✳️✳️ hostName: hmdemac-mini-local
operatingSystem
– (NSUInteger)operatingSystem API_DEPRECATED(“-operatingSystem always returns NSMACHOperatingSystem, use -operatingSystemVersion or -isOperatingSystemAtLeastVersion: Home “, macos (10.0, 10.10), the ios (2.0, 8.0), watchos (2.0, 2.0), tvos (9.0, 9.0));
Have been abandoned. Using operatingSystemVersion or isOperatingSystemAtLeastVersion: instead of.
Returns a constant indicating the operating system on which the process is executing.
Operating system identifier. See Constants for a list of possible values. In macOS, it is NSMACHOperatingSystem.
operatingSystemName
– (NSString *)operatingSystemName API_DEPRECATED(“-operatingSystemName always returns NSMACHOperatingSystem, Home use – operatingSystemVersionString “, macos (10.0, 10.10), the ios (2.0, 8.0), watchos (2.0, 2.0), tvos (9.0, 9.0));
Have been abandoned. Using operatingSystemVersionString instead.
Name of the operating system. In macOS, it is NSMACHOperatingSystem.
operatingSystemVersionString
The Human readable, localized; appropriate for displaying to user or using in bug emails and such; NOT appropriate for parsing
Human-readable, localized; Suitable for display to users or use in error emails, etc. Not suitable for parsing
@ property (readonly, copy) nsstrings * operatingSystemVersionString;
A string containing the operating system version of the executing process.
Operating system version strings are human-readable, localized, and suitable for display to users. This string is not suitable for analysis.
NSProcessInfo *processInfo = [NSProcessInfo processInfo];
// System version number
NSLog(@"✳ ️ ✳ ️ ✳ ️ operatingSystemVersionString: % @",processInfo.operatingSystemVersionString);
// Console prints✳ ️ ✳ ️ ✳ ️ operatingSystemVersionString: Version14.4 (Build 18D46)
Copy the code
operatingSystemVersion
@property (readonly) NSOperatingSystemVersion operatingSystemVersion API_AVAILABLE(MacOS (10.10), ios(8.0), Tvos watchos (2.0), (9.0));
The operating system version of the execution process.
isOperatingSystemAtLeastVersion:
– (BOOL) isOperatingSystemAtLeastVersion: (NSOperatingSystemVersion) version API_AVAILABLE (macos (10.10), the ios (8.0), Tvos watchos (2.0), (9.0));
Returns a Boolean value indicating whether the operating system version of the executing process is the same as or higher than the given version. The version parameter is the version of the operating system to be tested.
YES if the process is running on the same or newer operating system as the given version; Otherwise, NO.
This method describes the major, minor, and latest versions of the operating system.
Getting Computer Information
processorCount
@property (readonly) NSUInteger processorCount API_AVAILABLE(MacOS (10.5), ios(2.0), Watchos (2.0), TVOs (9.0));
The number of processing cores available on a computer.
The value of this attribute is the result of running the sysctl -n hw.ncpu command on the current system. (The result on my machine is: 16)
activeProcessorCount
@Property (readonly) NSUInteger activeProcessorCount API_AVAILABLE(MacOS (10.5), ios(2.0), Watchos (2.0), TVOs (9.0));
The number of active processing cores available on a computer.
The processorCount property reports the number of broadcast processing cores, while the activeProcessorCount property reflects the actual number of active processing cores on the system. There are many different factors that can cause core inactivity, including boot parameters, thermal limitations, or manufacturing defects.
The processorCount property reports the number of published processing cores, while the activeProcessorCount property reflects the actual number of active (or available) processing cores on the system. There are many different factors that can cause core inactivity, including boot arguments, thermal throttling, or manufacturing defect.
The value of this attribute is the result of running the sysctl -n hw. logicalCPU command on the current system. (8 on the M1 macMini)
physicalMemory
@property (readonly) unsigned long Long physicalMemory API_AVAILABLE(MacOS (10.5), ios(2.0), Watchos (2.0), tVOs (9.0));
The amount of physical memory, in bytes, on a computer. (That is, the current computer memory, for example my computer is 16 GB, the following code prints 16)
NSProcessInfo *info = [NSProcessInfo processInfo];
NSLog(@"🤯 🤯 🤯 % LLD." ", info.physicalMemory / 1024 / 1024 / 1024);
// Console print:
Test_ipa_simple[47082:3533173] 🤯 🤯 🤯16
Copy the code
systemUptime
@property (readonly) NSTimeInterval systemUptime API_AVAILABLE(MacOS (10.6), ios(4.0), Watchos (2.0), tVOs (9.0)); @property (readonly) NSTimeInterval systemUptime API_AVAILABLE(MacOS (10.6), ios(4.0), Watchos (2.0), tVOs (9.0));
The amount of time the system has been awake since the last reboot. (that is, the time since the last boot distance)
Managing Activities
– beginActivityWithOptions:reason:
@interface NSProcessInfo (NSProcessInfoActivity). -(id <NSObject>)beginActivityWithOptions:(NSActivityOptions)options reason:(NSString *)reason API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));. @endCopy the code
Pass in an activity to this API, and a non-null, non-empty reason string. Indicate completion of the activity by calling the corresponding endActivity: method with the result of the beginActivityWithOptions:reason: method. The reason string is used for debugging.
Calling this API starts an activity, passing in an activity type, and a non-null, non-empty cause string. By using beginActivityWithOptions: “reason: what was the result of the method (a pointer to the active object) call the corresponding endActivity: method to indicate that the activities completed. The reason string is used for debugging.
Options: Active options. The NSActivityOptions enumeration lists all of the possible values.
Reason argument: A string used for debugging to indicate why the activity started.
&esmp; The return value is a pointer to NSObject, which points to the active object. By calling endActivity: Pass the object returning the activity as a parameter to indicate the completion of the activity.
– endActivity:
@interface NSProcessInfo (NSProcessInfoActivity). -(void)endActivity:(id <NSObject>)activity API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));. @endCopy the code
Instance function that terminates a given activity (activeTY argument).
The activity parameters: beginActivityWithOptions: “reason: the function returns the active object.
performActivityWithOptions:reason:usingBlock:
@interface NSProcessInfo (NSProcessInfoActivity). -(void)performActivityWithOptions:(NSActivityOptions)options reason:(NSString *)reason usingBlock:(void (^)(void))block API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));. @endCopy the code
Synchronously Perform an activity. The activity will be automatically ended after your block argument returns. The reason string is used for debugging.
Perform an activity synchronously. The activity ends automatically when the block argument returns (that is, the block content completes execution). The Reason string is used for debugging.
Options parameters: Active options. The NSActivityOptions enumeration lists all possible values.
Reason argument: A string used for debugging to indicate why the activity started.
Block argument: Contains the content to be executed by the activity.
performExpiringActivityWithReason:usingBlock:
@interface NSProcessInfo (NSProcessInfoActivity). -(void)performExpiringActivityWithReason:(NSString *)reason usingBlock:(void(^)(BOOL expired))block API_AVAILABLE(ios(8.2), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos);. @endCopy the code
Asynchronously executes the specified block and notifies you when the process is about to hang.
Perform an expiring background task, which obtains an expiring task assertion on iOS. The block contains any work which needs to be completed as a background-priority task. The block will be scheduled on a system-provided concurrent queue. After a system-specified time, the block will be called with the expired parameter set to YES. The expired parameter will also be YES if the system decides to prematurely terminate a previous non-expiration invocation of the block.
Perform expired background tasks and obtain expired task assertions on iOS. This block contains any work that needs to be done as a background priority. The block will be placed in a system-provided concurrent queue. After the time specified by the system, the block is called with the expired parameter set to YES. If the system decides to prematurely terminate a previously unexpired block call, the expired parameter will also be YES.
Reason argument: A string used for debugging to indicate why the activity started. This argument cannot be nil or an empty string.
Block argument: The block that contains the content to be executed by the activity. The block returns no value and takes the expired argument of type BOOL as follows.
Expired parameter: A Boolean value indicating whether the process will be suspended. If the value is YES, the process will be suspended, so you should take whatever steps are necessary to stop the work in progress. If NO, the scheduled task is started.
Use this method to perform tasks while the process is executing in the background. This method queues blocks for asynchronous execution on concurrent queues. While your process is in the background, this method attempts to perform task assertions to ensure that your block has time to execute. If the task assertion cannot be executed, or the time allocated to the task assertion has expired, the system executes the block and sets the parameter to YES. If it can accept the task assertion, it will execute the block and pass NO for the expried argument.
If your block is still executing and the system needs to suspend the process, the system will execute your block a second time and set the expired parameter to YES. Your block must be prepared to handle this situation. When the expired parameter is YES, stop any ongoing tasks as soon as possible.
Getting the Thermal State
thermalState
@interface NSProcessInfo (NSProcessInfoThermalState)
@property (readonly) NSProcessInfoThermalState thermalState API_AVAILABLE(macosx(10.103.), ios(11.0), watchos(4.0), tvos(11.0));
@end
Copy the code
Retrieve the current thermal state of the system. On systems where thermal state is unknown or unsupported, the value returned from the thermalState property is always NSProcessInfoThermalStateNominal.
Retrieves the current thermal state of the system. In the thermal state is unknown or unsupported system, from the return value is always for NSProcessInfoThermalStateNominal thermalState attribute.
Returns the current hot state with the system of NSProcessInfoThermalState (an enumeration values). In high thermal states, your application should reduce the use of system resources. For more information, see NSProcessInfoThermalState enumeration.
• Determine Whether low-power Mode is Enabled.
lowPowerModeEnabled
@interface NSProcessInfo (NSProcessInfoPowerState) @property (readonly, Getter =isLowPowerModeEnabled) BOOL lowPowerModeEnabled API_AVAILABLE(ios(9.0), watchos(2.0), Tvos (9.0)) API_UNAVAILABLE (macos); @endCopy the code
Retrieve the current setting of the system for the low power mode setting. On systems where the low power mode is unknown or unsupported, the value returned from the lowPowerModeEnabled property is always NO
Set the current Settings for retrieving the system for low power mode. On systems where the low-power mode is unknown or unsupported, the value returned from the lowPowerModeEnabled attribute is always NO
A Boolean value indicating whether low power mode is enabled on iOS devices.
Users who want to extend their iPhone’s battery life can enable low Battery mode by going to Settings > Battery. In low power mode, iOS extends battery life by enacting certain energy saving measures, such as reducing CPU and GPU performance, reducing screen brightness, and suspending autonomous and background activities. Your application can query the lowPowerModeEnabled property at any time to determine if the low-power mode is active.
Your app can also register to receive notifications when the power status of your iOS device (low power mode enabled or disabled) changes. To register for a power supply state change notification, please send message addObserver: selector: name: object: send to the application’s default notification center (NSNotificationCenter instances). To pass it to invoke the selector and NSProcessInfoPowerStateDidChangeNotification notify name. Once the application receives notification of a change in power status, it should query isLowPowerModeEnabled to determine the current power status. If the low-power mode is active, the application can take appropriate steps to reduce the activity. Otherwise, normal operations can be restored.
For more information see Energy Efficiency and the User Experience React to Low Power Mode on iPhones.
NSProcessInfoPowerStateDidChangeNotification
FOUNDATION_EXTERN NSNotificationName const NSProcessInfoPowerStateDidChangeNotification API_AVAILABLE(ios(9.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos);
Copy the code
NSProcessInfoPowerStateDidChangeNotification is posted once any power usage mode of the system has changed. Once the notification is posted, Use the isLowPowerModeEnabled property to retrieve the current state of the low power mode setting of the system. When this notification is posted your application should attempt to reduce power usage by reducing potentially costly computation and other power using activities like network activity or keeping the screen on if the low power mode Setting is enabled. This notification is posted on the global dispatch queue. Register for it using the default notification center. The object associated with the notification is NSProcessInfo.processInfo.
Any power usage patterns change, once the system will release NSProcessInfoPowerStateDidChangeNotification. After a notification is published, use the isLowPowerModeEnabled property to retrieve the current status of the system’s low-power mode Settings. ; When this notice is published, your application should attempt to reduce power consumption by reducing potentially expensive computing and other usage activities (such as network activity) or by keeping the screen on when the low-power mode setting is enabled. This notification is published on the global scheduling queue. Register with the default notification center. Associated with notification object is the NSProcessInfo processInfo.
Publish (issue this notification) when the power status of an iOS device (enable or disable low-power mode) changes.
After the notification is published, query the lowPowerModeEnabled property to determine the current power status of the device. If the low-power mode is active, the application can take appropriate steps to reduce the activity. Otherwise, normal operations can be restored.
The notification object is the NSProcessInfo instance.
Constants
NSOperatingSystemVersion
typedef struct {
NSInteger majorVersion;
NSInteger minorVersion;
NSInteger patchVersion;
} NSOperatingSystemVersion;
Copy the code
Structure, operating system versions of the NSProcessInfo class attribute and isOperatingSystemAtLeastVersion operatingSystemVersion: method in use.
MajorVersion indicates the majorVersion number, such as 10 in 10.9.3.
MinorVersion Indicates the second version, for example, 9 in 10.9.3.
PatchVersion Updated version, for example, 3 in 10.9.3.
NSActivityOptions
typedef NS_OPTIONS(uint64_t, NSActivityOptions) {
// Used for activities that require the screen to stay powered on.
// Used for activities that require the screen to be turned on (the screen is always lit). . (1 moved 40 places to the left)
NSActivityIdleDisplaySleepDisabled = (1ULL << 40),
// Used for activities that require the computer to not idle sleep. This is included in NSActivityUserInitiated.
// Used for activities that require the computer not to sleep idle. This is included in NSActivityUserInitiated.
NSActivityIdleSystemSleepDisabled = (1ULL << 20),
// Prevents sudden termination. This is included in NSActivityUserInitiated.
// Prevent sudden termination. This is included in NSActivityUserInitiated.
NSActivitySuddenTerminationDisabled = (1ULL << 14),
// Prevents automatic termination. This is included in NSActivityUserInitiated.
// Prevent automatic termination. This is included in NSActivityUserInitiated.
NSActivityAutomaticTerminationDisabled = (1ULL << 15),
// ----
// Sets of options.
// Set of options
// App is performing a user-requested action.
// The application is performing the requested operation. (FLAG indicating that the application is performing the action requested by the user.)
NSActivityUserInitiated = (0x00FFFFFFULL | NSActivityIdleSystemSleepDisabled),
// flag to indicate that the application is performing the action requested by the user, but the system can sleep when idle.
NSActivityUserInitiatedAllowingIdleSystemSleep = (NSActivityUserInitiated & ~NSActivityIdleSystemSleepDisabled),
// App has initiated some kind of work, but not as the direct result of user request.
// flag indicating that the application has started some kind of work, but not as a direct result of a user request.
NSActivityBackground = 0x000000FFULL,
// Used for activities that require the highest amount of timer and I/O precision available. Very few applications should need to use this constant.
// For activities that require the highest available timers and I/O precision. Few applications need to use this constant.
NSActivityLatencyCritical = 0xFF00000000ULL,
} API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));
Copy the code
The system has heuristics to improve battery life, performance, and responsiveness of applications for the benefit of the user. This API can be used to give hints to the system that your application has special requirements. In response to creating one of these activities, the system will disable some or all of the heuristics so your application can finish quickly while still providing For the benefit of the user, the system has heuristics to improve the application’s battery life, performance, and responsiveness. This API can be used to alert the system that your application has special requirements. In response to creating one of these activities, the system will disable some or all of the heuristics so that your application can do it quickly, while still providing responsive behavior when the user needs it.
These activities can be used when your application is performing a long-running operation. If the activity can take different amounts of time (for example, calculating the next move in a chess game), it should use this API. This will ensure correct behavior when the amount of data or the capabilities of the user’s Computer varies. You should put your activity into one of two major categories: These activities are used when your app is being turned into long-running operations. Use this API if the activity is likely to take different times (for example, calculating the next step in a chess game). This ensures correct behavior in the event of changes in the amount of data or the functionality of the user’s computer. You should group your activities into one of two main categories:
The User initiated: These are finite length activities that the user has explicitly started. Examples include exporting or downloading a User specified file. User Initiated: These are limited length activities explicitly initiated by the user. Examples include exporting or downloading a user-specified file.
Background: These are finite length activities that are part of the normal operation of your application but are not explicitly Started by the user. Examples include autosaving, indexing, and automatic downloading of files. Background: These are finite-length activities that are part of the normal operation of the application, but are not explicitly initiated by the user. Examples include automatic saving, indexing, and automatic downloading of files.
In addition, if your application requires high priority IO, you can include the ‘NSActivityLatencyCritical’ flag (using a bitwise or). This should be reserved for activities like Audio or video recording. In addition, if your application requires a high-priority IO, you may include NSActivityLatencyCritical logo (using the bitwise or). This should be reserved for activities such as audio or video recording.
Synchronously takes place inside an event callback on the main thread, You do not need to use this API. You do not need to use this API if your activity occurs synchronously in event callbacks on the main thread.
Be aware that failing to end these activities for an extended period of time can have significant negative impacts to the performance of your user’s computer, So be sure to use only the minimum amount of time required. User preferences may override your application’s request. Please note that failure to end these activities for an extended period of time can have a significant negative impact on the performance of the user’s computer, so be sure to use only the minimum time required. Preferences may override requests for your application.
This API can also be used to control auto termination or sudden termination.
id activity = [NSProcessInfo.processInfo beginActivityWithOptions:NSActivityAutomaticTerminationDisabled reason:@"Good Reason"];
// work[NSProcessInfo.processInfo endActivity:activity];
Is equivalent to…
[NSProcessInfo.processInfo disableAutomaticTermination:@"Good Reason"];
// work[NSProcessInfo.processInfo enableAutomaticTermination:@"Good Reason"]
Since this API returns an object, it may be easier to pair begins and ends. If the object is deallocated before the -endActivity: Call, the activity will be automatically ended. Since this API returns an object, it may be easier to start and end pairing. If the object is released before -endActivity: is called, the activity ends automatically.
This API also provides a mechanism to disable system-wide idle sleep and display idle sleep. These can have a large impact on the user experience, So be sure not to forget to end activities that disable sleep (including NSActivityUserInitiated) A mechanism is also provided to disable system-wide idle sleep and to display idle sleep. These can have a big impact on the user experience, so make sure you don’t forget to end activities that disable sleep (including NSActivityUserInitiated).
Used for beginActivityWithOptions: “reason: function and performActivityWithOptions:” reason: usingBlock: option symbol of function.
To include one of these individual flags in one of the collections, use bitwise OR; For example, during a presentation, you might use:
NSActivityUserInitiated | NSActivityIdleDisplaySleepDisabled
Copy the code
To exclude from one of these collections, use bitwise AND AND NOT; For example, during user-initiated actions, if you log out, you can safely terminate the action without application interaction, you can use:
NSActivityUserInitiated & ~NSActivitySuddenTerminationDisabled
Copy the code
NSProcessInfoThermalState
// Describes the current thermal state of the system.
// Describes the current thermal state of the system.
typedef NS_ENUM(NSInteger, NSProcessInfoThermalState) {
// No corrective action is needed.
// No corrective action is required. (The thermal state is within the normal range.)
NSProcessInfoThermalStateNominal,
// The system has reached a state where fans may become audible (on systems which have fans). Recommendation: Defer non-user-visible activity.
// The system has reached the state where fans can be heard (on a system with fans). Suggestion: Postpone activities that are not visible to users.
NSProcessInfoThermalStateFair,
// Fans are running at maximum speed (on systems which have fans), system performance may be impacted. Recommendation: reduce application's usage of CPU, GPU and I/O, if possible. Switch to lower quality visual effects, reduce frame rates.
// The fan runs at maximum speed (on a system with a fan), and system performance may be affected. Suggestion: If possible, reduce the application's CPU, GPU, and I/O usage. Switch to a lower quality visual effect and lower frame rate.
NSProcessInfoThermalStateSerious,
// System performance is significantly impacted and the system needs to cool down. Recommendation: reduce application's usage of CPU, GPU, and I/O to the minimum level needed to respond to user actions. Consider stopping use of camera and other peripherals if your application is using them.
// System performance is significantly affected and system cooling is required. Suggestion: Reduce the application's CPU, GPU, and I/O usage to the minimum level required to respond to user operations. If your application is using cameras and other peripherals, consider discontinuing them.
NSProcessInfoThermalStateCritical
} API_AVAILABLE(macosx(10.103.), ios(11.0), watchos(4.0), tvos(11.0));
Copy the code
A value used to indicate the thermal state of a system.
The NSProcessInfo class uses these values as return values for the thermalState (thermalState).
For information about testing your app in different thermal states, see Test Under Adverse Device Conditions (iOS)
NSProcessInfoThermalStateNominal
NSProcessInfoThermalStateNominal thermal state in the normal range.
NSProcessInfoThermalStateFair
A slightly elevated NSProcessInfoThermalStateFair thermal state. The system takes measures to reduce the hot state, such as running fans and stopping background services that do not immediately perform the required work. Reduce or postpone background work, such as prefetching content over the network or updating database indexes.
NSProcessInfoThermalStateSerious
NSProcessInfoThermalStateSerious high thermal state. The system takes modest steps to reduce thermal states, which can degrade performance. The fan runs at maximum speed.
Reduce the use of resources that generate heat and consume batteries, such as:
-
Reduce or postpone I/O operations, such as networking and Bluetooth
-
Reduce the required level of positioning accuracy
-
Reduce CPU and GPU usage by stopping or delaying work
-
Reduced target frame rate from 60 FPS to 30 FPS
-
Reduce the level of detail in the rendered content by using fewer particles or lower resolution textures
For more details on how to reduce your application’s use of these resources, see Energy Efficiency and the User Experienc and Energy Efficiency Guide for Mac Apps.
NSProcessInfoThermalStateDidChangeNotification
FOUNDATION_EXTERN NSNotificationName const NSProcessInfoThermalStateDidChangeNotification API_AVAILABLE(macosx(10.103.), ios(11.0), watchos(4.0), tvos(11.0));
Copy the code
NSProcessInfoThermalStateDidChangeNotification is posted once the thermal state of the system has changed. Once the notification is posted, use the thermalState property to retrieve the current thermal state of the system. NSProcessInfoThermalStateDidChangeNotification thermal state of the system is changed after release. After a notification is issued, the thermalState property is used to retrieve the current hot state of the system.
You can use this opportunity to take corrective action in your application to help cool the system down could be done in the background or at opportunistic times should be using the Quality of Service levels in NSOperation Or the NSBackgroundActivityScheduler API. You can take advantage of this opportunity in the application to take corrective measures to help the cooling system. Can be done in the background or opportunistic time work should use NSOperation or NSBackgroundActivityScheduler API in the level of service quality.
This notification is posted on the global dispatch queue. Register for it using the default notification center. The The object associated with the notification is NSProcessInfo. ProcessInfo. This notice published on the global scheduling queues. Register it with the default notification center. Associated with notification object is the NSProcessInfo processInfo.
Is the name of a notification that is issued when the thermal state of the system changes.
At this point, the content of NSProcesshidp is all read, basically not difficult, suitable for quick browsing.
Refer to the link
Reference link :🔗
- IOS startup optimization + monitoring practices
- The first screen of The Hello Travel iOS App is optimized in seconds
- Tiktok RESEARCH and development practice: APP startup speed increased by more than 15% based on binary file rearrangement solution
- IOS App cold launch governance: From the practice of Meituan Waimai
- The most accurate way to record APP startup time
- How does iOS get the current time — just look at me
- Start the optimization
- IOS Optimization – Start optimization of Clang peg implementation binary rearrangement
- Lazy version binary rearrangement
- How did I get twitter Oasis to start up 30% faster
- App performance optimization summary