Simple iOS development instance and simple iOS development instance
Project requirements
Write an iPhone application. You can enter a name. After you click the button, a text message is displayed to greet the input name. For example, enter "" and the following message is displayed: "Hello, Baoyu !"
Requirement Analysis
This is a simple application that contains a text input box, a text display box, and a button. Enter the name in the text input box and click the button. Then, the text in the text display box becomes "Hello, <Name> !". However, note that if the user input is empty, a warning is required to prompt the user to re-enter the text. If the user input is too long and exceeds 16 characters, it must be automatically truncated.
Product Design
Draw a prototype diagram based on the project requirements:
Initial status
Initially, the text input box is empty, but the watermark is displayed, prompting you to enter a name. The text in the text display box is empty.
Enter the name and click the button.
Enter the name and click the button. The text in the middle of the screen is displayed: "Hello, <Name> !".
No warning prompt for name input
If no name is entered, click the button to bring up a warning window to remind the user to enter a name.
System Analysis
This is a very simple application, and the implementation is not complicated:
- A text input box is used to enter text. The maximum length of a character is 16 characters. When no content exists in the input box, the watermark text is displayed. The UITextField control can meet your needs.
- A text display box to display the final generated text. You can use the UILabel control to meet your needs.
- Click a button to obtain the text content in the text input box and generate "Hello, <Name> !" Text, and displayed in the text display box. If the text in the text box is blank when you click it, a warning box is displayed.
At the same time, this application needs to be applied to some common design patterns in iPhone development during development:
- Delegate)
- Model View Controller (MVC)
- Target-Action)
Delegate)
In the delegate mode, an object periodically sends a message to another object designated as its delegate, and sends a message to it for request input or notification that something is happening. This mode can replace class inheritance to extend the functions of reusable objects.
In this project, the application object will send a message to it, notifying it that its main startup routine has been completed and the customized configuration can be started. To create and manage a view, the delegate creates a controller instance. In addition, when you click Return, the text field will also notify its delegate (that is, the created controller object)
The delegate method is usually centralized to form an agreement. A protocol is basically a list of methods. If a class complies with a certain protocol, it must ensure the methods required by the implementation protocol (some methods can be implemented or not ). The delegate Protocol specifies all messages that an object can send to the delegate. For example, UITextFieldDelegate, UIApplicationDelegate, UIScrollViewDelegate, UITableViewDelegate, and UIWebViewDelegate.
Model View Controller (MVC)
In MVC mode, objects in an application are set to three roles: Model, View, and Controller ).
Model indicates data. For example, in an iPhone Address Book application, a contact is a model object, and a circle or rectangle is a model object in a painting application.
The data used by this project's application is very simple-a string, and this string is only used in the button-clicking method. In fact, from another perspective, the string is also the simplest model object. In other applications, the model object will be more complex and the model object is everywhere in the program, it can be accessed in multiple places.
View objects (Views) are used to display data. For example, UILabel can display text, UIImageView can display images, and users can edit data. For example, UITextField can support user input.
In the project to be created next, a main view is required to contain several other views. First, a text input box is used to capture user input information, and then a text display box, it is used to display text, while the text content is based on the user's input. In addition, a button is required to allow the user to click it and then notify the text field to be updated.
The Controller object is between the model and view.
In the project to be created next, when the user clicks the button and triggers the update operation, the Controller object will get the input text content from the text input box, store the text in a string, and then update the content of the text display box into formatted content.
In combination with the MVC mode, the main process of this project is as follows:
Target-Action)
The target-action mechanism allows a control object (such as a key or slider) to send a message (I .e. an action) to another object as a user event (such as a click event). The object that receives the message can respond to the message and process the message according to the business requirements.
In this project, when you click the button, it notifies the Controller to obtain the text input box content and update the text display box according to the input content.
Develop and create a project
We will start using Xcode to create a Project, start Xcode (by default, Xcode is located in/Developer/Applications), and select File> New Project, in this way, you can create a new project. You can see a new window, as shown in:
Select Window-Based Application, click Next, and enter Product Name (project Name): SayHello. In Company Identifier, you can enter the unique Identifier of the Company Name.
Click Next, select the project storage location, and click Create.
After completing the preceding steps, you will see the following new project window:
Before proceeding to the next step, you can compile and run the program so that you can see the program running on the simulator. Select Product> Run from the Xcode menu or click the Run button on the toolbar in the upper left corner. The iPhone simulator will automatically start. When the application starts, a white screen is displayed.
Analysis of Application Startup Process
When you create a project using the Xcode template, the template has helped you set up the basic application environment. It will help you create an application object and connect the application and window, create a runtime environment. The entire startup process starts with the UIApplicationMain function, as shown in:
The main function in the main. m file calls the UIApplicationMain function:
Int retVal = UIApplicationMain (argc, argv, nil, nil );
This function creates an instance of the UIApplicaion class. At the same time, it searches for the Info. plist attribute list file of the application. Info. A plist file is a dictionary that contains information such as application names and icons, it also contains the name of the nib file that the application object should load (although the file extension is "xib", but we call it "nib file. Nib files mainly contain user interface information. The Info. plist file of this project has the following content:
Term: although the extension of the Interface Builder document may be ". xib ", but in history, its extension is". nib (abbreviation of "NextStep Interface Builder"), which is commonly known as "Nib file ".
This indicates that the MainWindow nib file will be loaded when the application starts. In Xcode, you can click MainWindow. xib to view the file. (Note that you do not need to use Interface Builder to open the nib file in Xcode4. You can directly view and edit the nib file in Xcode ):
The MainWindow Nib document contains four objects:
- File's Owner, the proxy object of the File Owner. Here, when the Owner object of MainWindow is, the UIApplication instance
- First Responder, the First Responder proxy object, which is not used in this project
- Say Hello App Delegate, SayHelloAppDelegate instance, that is, application Delegate
- Window, a Window object. It is a white background by default, and what the program sees when it starts
After the application object is started, it will send the applicationDidFinishLaunching: Message to the delegate. The notification program has been started successfully, so that we can perform some operations as needed after receiving the message. Is a simplified iPhone application lifecycle diagram, which briefly shows the process from application startup to exit.
In this way, we have a basic understanding of how to create a project and the startup process of an application. Next, we need to create a View Controller instance to implement project functions.
Add a View Controller File
In iPhone applications, UIViewController plays a core role. As the name implies, the View Controller manages and controls the view. On the iPhone, they also help with navigation and memory management.
Select the project in Xcode project manager (that is, the SayHello project, located at the top of the Groups and Files list) or select the SayHello folder. When a new file is added, it is added to the selected location. Select File> New File from the Xcode menu. You can also right-click the selected folder and select New File.
In the New File window, select Cocoa Touch and then UIViewController subclass.
Click Next. In the Options window, select the check box "With XIB for user interface. After "With XIB for user interface" is selected, Xcode creates a nib file for the View Controller and adds the file to the project.
Click Next. In the save file window that appears later, name the file, for example, RootTimelineViewController, and select the file storage location, as shown below:
Click Save to add the file to the project. Next, we will create an instance of the controller class.
Create a View Controller instance
Now we have the View Controller class and nib file, but to use it in the application proxy, you must also create a class instance and store the instance in the variable, to operate on it.
In the header file (SayHelloAppDelegate. h) of the application delegate class, perform the following operations:
To access another class in one class, you must first reference the header file of the classes. Therefore, we first reference the header file of the View Controller (RootViewController) before the interface declaration of the application delegate header file (SayHelloAppDelegate. h)-that is, the SayHelloAppDelegate declaration:
# Import "RootViewController. h"
Then add the following code between the header file braces to add an instance variable to the application delegate:
RootViewController * viewController;
Add the following attribute declaration before @ end after braces:
@ Property (nonatomic, retain) RootViewController * viewController;
After adding the corresponding variables and attribute declarations to the header file, you need to synthesize the attribute access method in the corresponding implementation file and release the View Controller instance in the dealloc method.
In the implementation file (SayHelloAppDelegate. m) of the application delegate class, perform the following operations:
In the @ implementation code block of the class, notify the compiler to synthesize the access method for the View Controller:
@ Synthesize viewController;
Release the View Controller at the beginning of the dealloc method:
[ViewController release];
We have added the View Controller attribute to the application delegate. Now we need to create a View Controller instance and set it to the attribute value.
Add the following code at the beginning of applicationDidFinishLaunching in the application delegate class implementation file (SayHelloWorldAppDelegate. m) to create a RootViewController instance:
RootViewController * controller = [[RootViewController alloc] initWithNibName: @ "RootViewController" bundle: nil];
Self. viewController = controller;
[Controller release];
The function of this Code is as follows:
- Create a View Controller instance named RootViewController. Use the alloc method to create a View Controller, and then use the initWithNibName: bundle: Method to initialize it. The init method first specifies the nib file to be loaded by the Controller, and then specifies the package in which the file can be found. A package is an abstraction of a location in the file system. It stores the code and resources that the application will use.
- Use the attribute access method to set the created View Controller instance to the value of the viewController attribute variable.
- Release View Controller Based on memory management rules
View controllers are used to configure and manage the views seen in applications. Each view also corresponds to a View Controller for management. Window has a Root View Controller, which is used to configure the view that is first displayed when the form is displayed. To display the content of your View Controller in the form, you need to set the form's Root View Controller as your view controller.
Therefore, in our project, add a line of code after creating the View Controller instance code above to set the form Root View Controller as the newly added View Controller:
Self. window. rootViewController = controller;
The last line is the code automatically generated by the template provided by Xcode:
[Self. window makeKeyAndVisible];
This line of code will display the Window containing the View Controller view on the screen.
Complete code in this chapter: SayHelloAppDelegate. h file:
# Import <UIKit/UIKit. h>
# Import "RootViewController. h"
@ Interface SayHelloAppDelegate: NSObject <UIApplicationDelegate> {
RootViewController * viewController;
}
@ Property (nonatomic, retain) IBOutlet UIWindow * window;
@ Property (nonatomic, retain) RootViewController * viewController;
@ End
SayHelloAppDelegate. m file:
# Import "SayHelloAppDelegate. h"
@ Implementation SayHelloAppDelegate
@ Synthesize window = _ window;
@ Synthesize viewController;
-(BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions
{
RootViewController * controller = [[RootViewController alloc] initWithNibName: @ "RootViewController" bundle: nil];
Self. viewController = controller;
[Controller release];
Self. window. rootViewController = controller;
[Self. window makeKeyAndVisible];
Return YES;
}
-(Void) dealloc
{
[_ Window release];
[ViewController release];
[Super dealloc];
}
@ End
Test Run
Select Product> Run from the Xcode menu or click the Run button on the toolbar in the upper left corner. The iPhone simulator will automatically start. After the application starts, a white screen is displayed, but the white screen displayed for the first time is the Window in the application proxy. The white screen displayed this time is the view in the View Controller RootViewController.
Next, we will start editing the interface.
Edit Nib files
During iPhone development, The NIB file is generally used to display the interface, that is, the view object in the MVC model. The NIB file only contains the user interface elements and does not contain any source code, how can we associate a view object with a view controller? This requires two very important concepts: the outlet variable (outlet) and the File Owner proxy object (File's Owner ).
View Controller view and Nib file
View controllers are mainly responsible for configuring and managing all views in applications. Generally, view controllers are placed in a Nib file, and Nib files are not required, you can create a view by using a program. A typical View Controller such as UITableViewController does not need a Nib file. When creating a View Controller instance, one of the main ConstructorInitWithNibName: bundle:The first parameter is the name of the Nib file corresponding to the View Controller. The View Controller loads its Nib file in its loadView method. If you useInitWithNibName: bundle:The example generated by the constructor, and you want to perform additional settings after the view is loaded, you just need to override the viewDidLoad method of the View Controller.
In Xcode, click to open the View Controller's Nib file (namely, the RootViewController. xib file). In Xcode, you can directly view and edit the file. The File contains three objects: File Owner, First Responder, and View ). A View is the master View of the View Controller. You can add several subviews to the master View. The File Owner proxy (File's Owner) represents the View Controller class corresponding to the Nib File. It is important to understand the role of the file owner proxy and how to establish a connection between the file owner and interface elements in the Nib file.
Tip: When editing a Nib file in Xcode, you can click the toolbar in the upper right corner to hide the corresponding panel, which facilitates interface editing and attribute setting. File Owner)
In a Nib file, the file owner object is one of the most important objects, because it establishes a connection between the application code and the objects in the Nib interface file, specifically, it is the view controller object corresponding to the Nib file. Taking this project as an example, the file owner object of the RootViewController. xib Nib file is an instance of the RootViewController class.
Generally, when a template is used to create both the UIViewController file and the corresponding Nib file, it sets the file owner corresponding to the Nib file as the UIViewController class created by default. If you want to modify or set the file owner corresponding to the Nib file, you can use the Identity Inspector panel to set it.
Shows the RootViewController of this project. the owner of the file corresponding to the xib file. In the Class item of the Custom Class section on the Identity Inspector panel, the corresponding value is RootViewController, which indicates that the file owner is an instance of the RootViewController Class, in Xcode, you can access the IBOutlet attributes and IBAction methods in the file owner class, and establish associations with interface elements in the Nib file.
View socket variable
In Xcode, you can use the Inspector panel or the connection panel to view, create, and delete connections between objects. To view the connection of the View Controller, follow these steps:
In step 3 above, the connection panel displayed on the right side and the translucent connection panel popped up by right-click File's Owner. The displayed information and functions are the same and can be used flexibly according to your personal habits. So far, the only connection is the view outlet variable of the view Controller. A socket variable corresponds to an attribute of the View Controller class (sometimes an instance variable), except that this attribute is connected to an interface element in the nib file. The view connection indicates that when the nib file RootViewController. xib is loaded and the UIView instance files are Unarchived, the view instance variable of the view Controller is set to point to the view in the nib file.
Intermediate Test
During project development, especially when you are not familiar with development tools and languages, you need to regularly test new functions to ensure that the current functions run normally. For example, if we have added the custom View Controller RootViewController, we need to test whether it has been successfully added. To test whether the View Controller works normally, you can simply modify the background color of the View Controller. For example, change it to a pink background and run the command again to see if the interface has changed to a red background.
To set the background color of the View Controller, follow these steps:
Under normal circumstances, there should be no compilation errors. After running, the simulator will pop up. The result is shown in:
After confirming that there is no problem, restore the background color of the application. If it is restored, set the background color of the view to white.
Configuration View
Xcode provides a set of object libraries that can be directly added to the Nib file. Some of them show interface elements, such as buttons and text input boxes; others are controller objects, such as view controllers. The nib file of our current project already contains the view. Now we only need to add the button and text input box. Drag the user interface elements from the object library to the view. The basic steps are as follows:
If we want users to have a better experience when entering the English name, the first letter is capitalized by default. For example, the keyboard displays the completed button, click it and enter the hidden keyboard. To support such input details, you can set the attributes of the text box:
- In the Capitalization drop-down list, select Words to enable uppercase letters.
- In the Return Key drop-down list, select Done to enable the Done button on the keyboard.
After saving the file, compile and run the program. You can see that the running interface has the same effect as the display in Xcode. Click the button to highlight it. In the text input box, the Input Keyboard is displayed, and The Done button is displayed on the keyboard. However, the text cannot be displayed based on the input content, and the keyboard cannot be hidden, because we have only completed the work of the view, you also need to establish a connection between the object in the view and the object in the View Controller, and add the corresponding logic.
View Controller implementation
To implement the View Controller, you must do the following:
Establish a connection
From the business perspective, we need to establish an association with several elements of the interface:
Before Xcode4, Interface Builder and Xcode are separated. Generally, the socket variables and action methods are defined in Xcode, then establish the connection between the Interface element and the View Controller in InterfaceBuilder. After Xcode4 is reached, the Interface Builder and Xcode have been merged together, so there are some changes in this part, xcode4 makes this part of work easier. You can drag it directly from the view editing interface to connect to the code file.
In the SayHello project we are developing, we need to add an Action Method to the View Controller. When the button on the interface is clicked, it will send a sayHello: Message to the View Controller, therefore, create a sayHello: Action Method for the button:
You have done two things by adding an action for the button.
Next, we need to establish a connection between the text input box and text Tag:
The preceding operation to add a socket variable to the text input box completes two tasks:
Follow the above method to create the same socket variable in the text input box, create the socket variable used to display the text label of the greeting, and name the socket variable as greetingLabel with the type of UILabel.
Implement logic code
Click the button in the view to send the sayHello: Message to the View Controller. After that, the View Controller obtains the text content of the text input box and updates the text TAG content used to display the greeting. The following is the sayHello in the RootViewController. m file: Implementation of the method code:
-(IBAction) sayHello :( id) sender {
// Obtain the content of the text input box and store it in the Variable
NSString * nameString = nameTextField. text;
// Check whether the input name is null. If it is null, a prompt is displayed.
If (nameString. length = 0 ){
UIAlertView * alertView = [[UIAlertView alloc] initWithTitle: @ "name cannot be blank" message: @ "enter a name and click the button again. "Delegate: nil cancelButtonTitle: @" OK "otherButtonTitles: nil, nil];
[AlertView show];
[AlertView release];
GreetingLabel. text = @"";
Return;
}
// Check whether the name is more than 16 characters. If the name is more than 16 characters, it is automatically truncated.
If (nameString. length> 16 ){
NameString = [nameString substringToIndex: 16];
}
// Generate a greeting based on the input name
NSString * greeting = [NSString stringWithFormat: @ "Hello, % @! ", NameString];
// Display greetings
GreetingLabel. text = greeting;
}
There are several additional instructions for this method:
- UIAlertView is used to display the message prompt dialog box.
- StringWithFormat: The method string creates a new string according to the format specified by the formatted string. % @ Indicates that a String object should be used here.
Hide keyboard
Compile and run the application. Enter "Jim" in the text box, click the button, and the label displays "Hello, Jim !" . However, if you select a text field for input, you will find that you have no way to indicate that the input is complete, and there is no way to eliminate the keyboard. In iPhone applications, when an element that allows text input becomes the first responder, the keyboard is automatically displayed. When the element is no longer in the first responder status, the keyboard disappears. We cannot directly send messages to the keyboard, but we can switch the first responder status of the text input element, and use the additional effect of this operation to display or remove the keyboard. In the application, when a user clicks a text field, the control becomes the first responder, so the keyboard is displayed. When you click the Done button on the keyboard, you want the keyboard to disappear.
The UITextFieldDelegate protocol contains a textFieldShouldReturn: method. Once you click Return, the text field will call this method (it has nothing to do with the title of the button ). However, this method can be implemented only by setting the View Controller to the Delegate of the UITextField. In the method, the resignFirstResponder message is sent to the text field, the additional effect of this message will make the keyboard disappear.
Follow these steps to set the delegate connection in the text input box:
Next, use RootViewController as the delegate (delegate) of the text input box nameTextField)
Now we have developed the entire application. Next we will test it.
Test
This application is relatively simple. We design several test scenarios:
For this test scenario, perform functional tests one by one. The results seem to be exactly the same as we expected.
A summary of the following knowledge points through a simple project:
- Common design modes for iOS development
- IPhone program Startup Process
- How to establish a connection between the View Controller and the Nib file
This knowledge is frequently used for iPhone development and iOS development.
Is it easy to learn about android development or ios development?
Android requires a java Foundation, and ios requires a certain C language basis (using Objective-C ).
However, in the development process, ios development is relatively simple. Many of its methods are implemented through connections, saving a lot of code.
I want to develop simple ios games
Individual developers pay more than 600 RMB for one year of SDK Usage After registering with apple
Company-level sdks require thousands or even tens of thousands of RMB a year, but they are not expensive.
Then download the development environment to your computer for development.