IPhone application programming guide (core applications)

Source: Internet
Author: User
Tags sqlite database home screen reverse dns

 

Core Application Architecture

Application Lifecycle

 

Main Function

mainThere are only three things to create a routine:Auto Release pool, CallUIApplicationMainFunction, and use the Auto Release pool.

Application Delegation

The advanced behavior of monitoring applications is the applicationDelegateThe application delegate object is the custom class instance you provide.

The application's delegate object is responsible for processing several key system messages. Every iPhone application hasRequiredThere is an application delegate object that can be an instance of any class you want, but you need to followUIApplicationDelegateProtocolThe Protocol method defines some hooks in the application lifecycle. You can use these methods to customize the behavior.

Event processing cycle

After the application is initialized,UIApplicationMainThe function starts the basic component for managing application events and plotting cycles, as shown in figure 1-2. When the user interacts with the device, the iPhone OS detects the touch event and puts the event into the event queue of the application. Then,UIApplicationThe event processing facility of an object extracts events one by one from the top of the queue and distributes the events to the objects most suitable for processing.

In the iPhone OS multi-touch event model, the touch data is encapsulated in the event object (UIEvent. To track touch actions, the event object contains some touch objects (UITouch), Each touch object corresponds to a finger that is touching the screen. When you place your fingers on the screen, move them around, and finally exit the screen, the system reports changes to each finger through the corresponding touch object.

 

When an application is started, the system creates a process and a single thread for the program. This initial thread becomes the main thread of the application,UIApplicationThe object is created in this thread.Main running cycleAnd configure the event processing code of the application. Figure 1-3 shows the relationship between the event processing code and the main running cycle. The Touch event sent by the system will wait in the queue until it is processed cyclically by the main running of the application.

Note:The running cycle monitors the Input Source of the specified execution thread. When the input source has data to be processed, the running loop will wake up the corresponding thread and give control to the processor code of the Input Source. After the processor completes the task, it returns the control to the running loop. Then, the running loop processes the next event. If there are no other events, running the loop will bring the thread into sleep state. You can useNSRunLoopClass to install its own input source, including the port and timer.

UIApplicationThe object uses an input source for processing touch events to configure the main running cycle, so that the touch events can be distributed to appropriate responder objects. The recipient object is inherited fromUIResponderClass, which implements one or more event methods to process events in different stages of a touch event. Application response objects includeUIApplication,UIWindow,UIView, And allUIViewSubclass instance. Applications usually distribute eventsUIWindowObject, and then the window object sends the event to itsFirst responderIs usually a view object that has a touch event (UIView).

Responder link: It is composed of a group of responder objects linked together in an application, usually starting with the first responder. When an event occurs, if the first responder object cannot be processed, it is passed to the next object in the responder chain. Messages continue to be transmitted in the chain-from underlying responder objects to advanced responder objects such as Windows, applications, and application delegation-until the event is processed. If the event is not processed, it will be discarded.

Basic Design Model

Model-View-controller delegate target-Action delegate Memory Model

 

The application running environment starts quickly and takes a short time to use.

In addition to Quick Start, your application must be prepared for quick exit. Every time a user leaves your application, the iPhone OS will notify you to exit, whether you press the Home key or open another application through the features provided by the software. At that time, you need to save unsaved changes to the disk as soon as possible. If your application exits for more than five seconds, the system may immediately terminate it.

Application sandbox

In iPhone OS, applications and their data reside in a safe place, and other applications cannot access them.

After the application is installed, the system obtains an opaque identifier through computation, and then constructs a path pointing to the application home directory based on the root directory and identifier of the application. Therefore, the home directory of the application has the following structure:

  • /ApplicationRoot/ApplicationID/

During the installation process, the system will create the home directory and several key subdirectories of the application, configure the application sandbox, and copy the application package to the home directory. Placing applications and their data in a specific place can simplify backup and recovery, and simplify application update and uninstallation.

Virtual Memory System

In iPhone OS, each program still has its own virtual address space, but its available virtual memory is limited by the number of existing physical memory (which is different from Mac OS X ). This is because when the memory usage is full, the iPhone OS does not write non-permanent memory pages to the disk. Instead, the virtual memory system releases nonvolatile memory as needed to ensure that the required space is provided for running applications. Memory is released by deleting memory pages that are not currently in use or contain read-only content (such as code pages, such pages can be reloaded to the memory when they need to be used later.

Automatic Sleep Timer

ShareUIApplicationObjectidleTimerDisabledSet propertyYESTo disable the automatic Sleep Timer.

 

Application Package

PackageIs a directory in the file system, used to set Execution Code and related resources in one place.

Info. plist

By default, xcode does not directly display the actual key names. Therefore, the following table lists the strings that these keys display in xcode. You can view the actual key names of all keys. Press and hold the control key, click the information attribute list item in the editor, and select the show raw keys/values command in the context menu.

If the property value in the information property file is a string displayed on the user interface, it should be localized, especially whenInfo.plistInInfoPlist.stringsFile.

Application icons and startup Images

To add an image file to the xcode project, select the add to project command from the project menu, locate the target file in the browser, and click Add.

 

Process key application task initialization and Termination
Table 1-5Application delegate responsibility

Delegate Method

Description

applicationDidFinishLaunching:

Use this method to restore the application to the status of the previous session. You can also execute the application data structure and custom Initialization on the user interface in this method.

applicationWillTerminate:

This method is used to store data or key application states to disks. You can also perform additional cleanup operations in this method, such as deleting temporary files.

Response interruption

In addition to the Home button, the system can temporarily interrupt your application to respond to important events. For example, an application may be interrupted by incoming calls, SMS messages, calendar warnings, or Sleep buttons on the device. Pressing the Home button will terminate your application, and the above interruptions are only temporary. If the user ignores these interruptions, your application can continue to run as before; however, if the user decides to answer the phone or respond to SMS information, the system will start to terminate your program.

Figure 1-6Event process during interruption

Depending on the user's response to the interruption, the system may start your application again after the interruption ends. For example, if a user receives a call and hangs up after the call is complete, the system restarts your application. If the user returns to the Home screen or starts another program during the call process, then the system will no longer start your application.

Important:When a user receives a call and restarts your application during the call, the height of the status bar increases to reflect that the current user is on the call. Similarly, when a user finishes a call, the height of the status bar is reduced to the normal size. Your application should be prepared for changes to the status bar height and adjust the size of the content area accordingly. The View Controller automatically handles this behavior. However, if you use code to layout the user interface, you needlayoutSubviewsWhen handling dynamic layout changes, consider the height of the status bar.

When running your application, if you press the sleep/Wakeup button of the device, the system callsapplicationWillResignActive:Method To stop the dispatch of touch events, and then enable the device to sleep. Then, when the user wakes up the device, the system callsapplicationDidBecomeActive:Method, and then start distributing events to the application again. Like handling other interruptions, you should use these methods to sleep the application (or pause the game) and wake it up again. During sleep, your application should use as little power as possible.

 

Observe low memory warning

UIKit provides the following methods to receive low-memory Warnings:

  • Implemented in application delegateapplicationDidReceiveMemoryWarning:Method.

  • In yourUIViewControllerImplementation in subclassdidReceiveMemoryWarningMethod.

  • RegisterUIApplicationDidReceiveMemoryWarningNotificationAnnouncement.

     

Customize application behaviors to start in Landscape mode
  • InInfo.plistAdd to fileUIInterfaceOrientationAnd set its value to Landscape mode. You can set this key valueUIInterfaceOrientationLandscapeLeftOrUIInterfaceOrientationLandscapeRight.

  • Deploy your view in Landscape mode, and ensure that the automatic size adjustment options of the view are correctly set.

  • Overload View ControllershouldAutorotateToInterfaceOrientation:Method so that it returns only in the desired landscape directionYESIn the portrait direction.NO.

UIInterfaceOrientationProperty prompts that the iPhone OS should configure the application status bar (if any) at startup, just like configuringView ControllerThe view direction under management is the same. In iPhone OS 2.1 and later versions, the View Controller respects this attribute and sets the initial direction of the view to the specified direction. Using this attribute is equivalentapplicationDidFinishLaunching:Method execution at the beginningUIApplicationOfsetStatusBarOrientation:animated:Method.

Communicate with other applications

If an application supports some known types of URLs, you can communicate with the program through the corresponding URL mode. However, in most cases, URLs are only used to simply start an application and display information related to the caller.

Built-in support for Applehttp,mailto,tel, AndsmsThese URL modes also supporthttpMaps, YouTube, and iPod URLs. Applications can also register custom URL modes.

NSURL *myURL = [NSURL URLWithString:@"todolist://www.acme.com?Quarterly%20Report#200806231300"];
[[UIApplication sharedApplication] openURL:myURL];

Important:If your URL type contains the same pattern as that defined by Apple, it starts the program provided by Apple, not your program. If there are multiple third-party applications registered to process the same URL mode, the type of URL is not defined by which program.

Implement custom URL Mode

You can register a URL type that contains a custom mode for your application. The custom URL mode allows third-party applications to interact with other programs and systems. Through the custom URL mode, the application can provide its own services to other programs.

Register the custom URL Mode
Table 1-6 CFBundleURLTypesAttribute keys and values

Key

Value

CFBundleURLName

This is a string that indicates the abstract name of the URL type. To ensure its uniqueness, we recommend that you use reverse DNS-style identifiers, suchcom.acme.myscheme.

The URL type name provided here is a key pointing to a localized string, which is located in the subdirectory of the localized Language PackInfoPlist.stringsFile. A localized string is a recognizable URL type name in a language.

CFBundleURLSchemes

This is an array of URL patterns, indicating that the URL belongs to this URL type. Each mode is a string. URLs of the specified URL type all carry their pattern components.

Process URL requests

The application is delegatedapplication:handleOpenURL:Method. If you have registered a custom URL mode for your application, you mustDelegate.

The protocol used by the URL Based on the custom mode is understandable to the application requesting the service. The URL contains the desired information of the registration mode application, which is required by the program to process or respond to the URL request. Passapplication:handleOpenURL:MethodNSURLThe object represents the URL in the Cocoa Touch framework.NSURLFollowing the RFC 1808 standard, this class contains some methods used to return each URL element defined in RFC 1808, including the user name, password, request, segment, and parameter string. The "protocol" corresponding to your registered custom mode can use these URL elements to transmit various information.

Verify the input URL. If you want to know how to avoid URL Processing problems, seeSecurity coding GuideVerification input in this document. For more information about the URL mode defined by Apple, seeApple URL mode reference.

Show application preference settings

If your application uses preference settings to control different aspects of its behavior, the way in which preference settings are provided to users depends on whether they are necessary for the program.

  • If preference settings are necessary for the Program (and are easy to implement directly), they should be presented directly through the custom interface of the application.

  • If preference settings are not required and require relatively complex interfaces, they should be presented through the system settings program.

When determining whether a set of preference settings are necessary for a program, consider the use mode you designed for the program. If you want users to modify preference settings relatively frequently, or these preference settings have a relatively important impact on program behavior, it may be necessary.

Set packageIs a custom resource located at the top of the application's package directory. It is an encapsulated directory namedSettings.bundle. The configuration package contains some data files with special formats (and their supported resources). It is used to tell the Settings program how to display your preference Settings. These files also tell the Settings program where to store the result value in the preference database so that the application can thenNSUserDefaultsOrCFPreferencesAPI.

Internationalization of your applications

Language andPackageA sub-directory is associated. The sub-directory name consists of two parts: the language code defined by ISO 639-1 and.lprojSuffix. You can also modify the language code to include a specific region by adding an ISO-6-1 regional indicator to the end (after the underline. For example, if you want to specify a localized resource for US English, the subdirectory in the package should be nameden_US.lproj. We agree that the subdirectory of the localization language is calledlprojFolder.

Optimization of performance and response speed should not block the main thread

You should carefully consider the tasks executed on the main thread of the application. The main thread is where the application processes touch events and other user input. To ensure that applications can always respond to users, we should not execute tasks that run for a long time or may wait infinitely in the main thread, such as network access tasks. Instead, you should place these tasks in background threads. A recommended method is to encapsulate each task in an operation object and then add it to the operation queue. Of course, you can also create an explicit thread on your own.

Transferring a task to the background allows your main thread to continue processing user input, which is especially important for application startup and exit. At these times, the system expects your application to respond to events in a timely manner. If the main thread of the application is blocked during startup, the system may even kill it before the startup is completed. If the main thread is blocked when it exits, the application may be killed if it is too late to save key user data.

Effectively use memory to reduce the memory footprint of applications
Table 1-7Tips for reducing application memory footprint

Tips

Measures Taken

Eliminate Memory leakage

As memory is a key resource of the iPhone OS, your application should not have any memory leakage. Memory leakage means that the application may not have enough memory later. You can use the Instruments program to track code leaks. This program can be used either as a simulator or as an actual device. For more information about how to use Instruments, seeInstruments User Guide.

Make the resource file as small as possible

Files reside on the disk, but the memory needs to be loaded during use.Attribute listFiles and image files are two types of resources that can save space by simple processing. You can useNSPropertyListSerializationClass stores attribute list files in binary format to reduce their usage space. For images, all image files can be compressed as small as possible (PNG images are recommended image formats for iPhone applications and can be usedpngcrushTool ).

Use Core Data or SQLite to handle large Data sets

If your application requires a large amount of structured Data, store it in the persistent storage of Core Data or SQLite database, instead of using flat files. Both Core Data and SQLite provide effective methods for managing a large amount of Data without loading the entire Data into the memory at a time.

Core Data support is introduced on the iPhone OS 3.0 system.

Delays loading resources

Before you really need resource files, you should never load them. Loading resource files in advance seems to save time, but it actually slows down the application. In addition, if you do not use those resources in the end, pre-loading will be a waste of memory.

Concatenate programs into Thumb format

Join-mthumbThe switch can reduce the code size by up to 35%. However, for code modules with a large number of floating point operations, Please disable this option, because using Thumb for such modules will lead to performance degradation.

Properly allocate memory
Table 1-8Memory Allocation skills

Tips

Measures Taken

Reduce the use of automatically released objects

PassautoreleaseObjects released by the method will remain in the memory until the automatically released pool is cleared explicitly or the program returns to the event loop again. Avoid usingautoreleaseMethod, but throughreleaseMethod to immediately reclaim the space occupied by the object. If you must create a certain number of automatic release objects, create a local automatic release pool to clear them regularly before returning the event loop and reclaim the memory of those objects.

Set size limits for resources

Avoid loading large resource files if smaller files are available. Replace high-definition images with appropriate size images for iPhone OS devices. If you must use a large resource file, consider loading only the required parts. For example, you can usemmapAndmunmapFunction to load a part of the file into the memory or detach from the memory, instead of operating the entire file. For more information about how to map files to memory, seeFile System Performance Guide.

Avoid borderless problem sets

The borderless problem set may need to calculate any large amount of data. If the set requires more memory than the current system can provide, your application may not be able to compute. Your applications should try to avoid processing such collections and convert them into problems with known memory usage limits.

Floating Point mathematical operations to reduce power consumption

You can improve the battery life by optimizing the usage of the following components:

  • CPU

  • Wi-Fi and baseband (EDGE, 3G) wireless signals

  • Core Location framework

  • Accelerator

  • Disk

Your optimization goal should be to do most of the work as effectively as possible. You should always use the Instruments and Shark tools to optimize the application algorithm. However, it is important that even the optimal algorithm may negatively affect the battery life of the device.


The more data you transmit to the network, the more energy you need for wireless transmission. In fact, accessing the network is the most energy-consuming operation you can do.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.