Objective-C 2.0 with cocoa Foundation-2, from Hello, world! Start

Source: Internet
Author: User
Tags string methods
ArticleDirectory
    • 2, from Hello, world! Start
2, from Hello, world! Start

This series of lectures has a strong correlation. If you are reading this article for the first time and want to better understand the content of this chapter, I suggest you read it from Chapter 1 of this series of lectures, click here.

Now I assume that you have a development environment. Okay, let's start building our firstProgram.

Before starting the first program, I need to remind you that if you have a development environment in your hands and are in close contact with xcode for the first time, in order to be familiar with the development environment, we strongly recommend that you follow the steps in step by step. Despite this, I have prepared some suggestions for you.Code, Click here to download.

2.1, build Hello, world

Step 1: Start xcode. At the first startup, a "Welcome to xcode" dialog box may pop up. This dialog box has nothing to do with our topic. We can turn it off.

Step 2: Select "file-> New Project" in the top menu of the screen. A dialog box is displayed, showing you the options for the project type. Select "command line utility" on the left of the dialog box, select "Foundation tool" on the right, and select "choose. 2.1.

 

Figure 2-1 create a project

Note:

Someone may ask, why don't you choose "application" under "iPhone OS" if you want to explain iPhone development?
This is the case. In this series, I mainly focus on the explanation of objective-C syntax. In order to make the explanation simple and easy to understand, I will clear all things irrelevant to the content to be explained, so here I am only using the simplest command line.

 

Step 3, xcode will ask your project name, enter "02-Hello World" in "Save as", and then select "save ". 2-2

 

Figure 2-2 enter the project name

Step 4: Get a picture shown in 2-3. Click "02-Hello World" and "Source" in the Left window respectively ". "Documentation", "external frameworks and libraries", "products", and then observe what appears in the window on the right. In general, "02-Hello world" is the list of all files under the project name. The subdirectories under the project are virtual or actual directories related to the project. Why is it virtual? You can open the directory of your project files through the finder. You will find that all your files are under the root directory, and there is no directory such as "Source.

 

Figure 2-3: Project browsing window

Step 5: Select "run" in the menu at the top of the screen and select "console". The screen is displayed as shown in 2-4. Click "Build and go" in the middle of the window.

 

Figure 2-4: running result Screen

If nothing happens, you should see the "Hello wolrd!" That we are not familiar !" . Since we have not written any code, theoretically, this part of the Code should not be compiled incorrectly. Okay. Now, I want to explain some new things in Hello world.

2.2. Import the header file

In Java or C/C ++, when our program needs to reference external classes or methods, the program source file must contain external classes and methods (jar package in Java) or header files (C/C ++. h), there are similar mechanisms in objective-C. In this section, I will introduce how the header file is included in objective-C.

Invite students to the xcode Development EnvironmentIn the left-side window, click the source folder and you will see the list of source code files in the right-side pane. Find 02-Hello world. m and then click it to appear in the xcode window. Double-click the mouse and the code will appear in a new window. Please follow this method.Open "02-Hello world. m ".

For Java programs, the source program suffix is. java. For C/C ++ code, the suffix is C/CPP. Now we have encountered. M. After xcode sees the. M file, it will compile the file as an objective-C file. Students may guess that when xcode encounters C/CPP or Java, it will also correspond to the corresponding language.

Okay. By the way, we mentioned xcode's Convention on the. M file. Now let's start with the first line of code. Please refer to the following code:

1 # Import < Foundation / Foundation. h >
2
3 Int Main ( Int Argc, Const   Char   * Argv []) {
4 NSAID utoreleasepool * Pool = [[NSAID utoreleasepool alloc] init];
5
6 // Insert code here
7 Nslog ( @" Hello, world! " );
8 [Pool drain];
9 Return   0 ;
10 }
11


# Import<Foundation/Foundation. h>

int main ( int argc, const char * argv []) {
nfutoreleasepool * pool = [[NSAID utoreleasepool alloc] init];

//Insert code here
Nslog (@"Hello, world!");
[Pool drain];
Return 0;
}

Those who have experience in C/C ++ may feel a little kind when they see the first line. Those who have experience in Java may also feel familiar when they see the first line. You may have guessed what this is for. That's right. This is the header file. However, in C/C ++, it is # include, in Java, It is import, and here it is # import.

In C/C ++, there will be # include mutual inclusion issues. In this case, # ifdef is required for compilation guidance. In xcode, students can "Safely" include various things, this does not matter, because our compiler is "smart" enough, because the same header file is only imported once. Except that # import is a bit smarter, it has the same functionality as # include.

Let's take a look at another new friend, foundation. h. This is the header file of the system framework foundation framework. With this header file, you can obtain the system for free or a series of system functions that Apple has carefully prepared for you, such as string operations. The foundation framework belongs to the cocoa framework set. Another cocoa framework is Application Kit or uikit. The former applies to Mac OS, and the latter applies to iPhone OS. This series of Getting Started Guide will only use Foundation, because I need to introduce the basic use of objective-C to students, in order to avoid reading difficulties caused by too many new things, therefore, the command line is enough.

Speaking of this, I need to clarify that the cocoa of Mac OS is different from that of iPhone. It can be said that iPhone is a subset of Mac OS.

2.3, Main Function

Those who have experience in C/C ++ or Java should be familiar with the 3rd-line code. This main is exactly the same as the main in the C/C ++ language, and is essentially the same as the Java language. Because objective-C fully inherits the features of C. Specifically, it is not that objective-C is very similar to C, but that objective-C is fully compatible with C.

I am not here to discuss what the main function is for. If you are interested, you can find a C-language book.

2.4. About NSAID utoreleasepool

Do it by yourself ---

In row 3, we met another new thing, which is the NSAID utoreleasepool.

Let me divide this word into three parts: NS, autorelease, and pool.

When we see NS, we may not know what it represents. NS is actually a prefix to avoid naming conflicts. NS comes from a software of nextstep, short for next software. Next software is the predecessor of cocoa and used NS at the beginning. To maintain compatibility, NS has been retained. To avoid name conflicts during development by multiple developers, it is best for developers to define their respective prefixes in advance. However, it is recommended that you do not use the NS prefix, which may lead to misunderstandings.

Unfortunately, objective-C does not support the namespace keyword and does not know whether the keyword will be supported in later versions.

Next we will discuss autorelease and pool.

When the program is running, it needs to apply for memory space from the system. When the memory space is no longer used, there is no doubt that the memory needs to be released, otherwise, the limited memory space will soon be used up, and the subsequent programs will not be able to get the effective memory space for execution. Since the birth of computer technology, countless programmers and countless our predecessors have been working hard to manage memory. Since then, the management of memory has been greatly improved.

There are three memory management methods in objective-C or cocoa.

The first type is "Garbage Collection ". This method is similar to Java. During the execution of your program, there is always a high person behind the scenes to help you clean up the garbage accurately. You don't have to consider when it starts to work or how it works. You only need to understand that I have applied for a piece of memory space. When I no longer use the memory and it becomes garbage, I will completely forget it, the tall guy will help me clean up the garbage. Unfortunately, that person needs to consume a certain amount of resources. In the carrying devices, the resources are very popular, so the iPhone does not support this function. Therefore, "Garbage Collection" is not the scope of this Getting Started Guide. If you are interested in the internal mechanism of "Garbage Collection", you can refer to other materials, but to be honest, "Garbage Collection" is not suitable for beginners.

The second type is "reference counted ". That is to say, after a memory segment is applied, there is a variable used to save the number of times this memory segment is used. We call it a counter for the moment. When the counter changes to 0, this is the time to release the memory. For example, after a memory segment in program a is successfully applied for, the counter changes from 0 to 1 (we call this process alloc ), then program B needs to use this memory, and the counter is changed from 1 to 2 (we call this process retain ). Then, when program a no longer needs the memory, program a will reduce the counter by 1 (we call this process release); and program B no longer needs the memory, then, reduce the counter by 1 (this process is still release ). When the system (that is, the Foundation) finds that the counter has changed to 0, it will call the memory recycle program to recycle the memory (we call this process dealloc ). By the way, if there is no foundation, you need to manually maintain the counter, release the memory, and so on.

In this way, we can easily control the memory when we do not know whether a does not use this memory or B does not use this memory. Otherwise, when we release the memory in program a, we also need to check whether program B is still using the memory. Otherwise, after program a releases the memory, poor Program B will be unable to use this memory. This method is very important, especially in multi-threaded programs. If multiple threads use a certain piece of memory at the same time, safe control of these memories has become a nightmare for many talented programmers.

If you have worked on com, you should be familiar with release/addref. In fact, obejctive-C is the same as their mechanism.

Next, I need to explain the autorelease method. The above alloc-> retain-> release-> dealloc process looks satisfactory, but sometimes it is not very convenient, and our code looks awkward. At this time, we need autorelease. Autorelease means that this process is maintained in the thread instead of reducing the counter by 1 immediately. When a thread starts, it needs to notify the thread (ngutoreleasepool) to release the memory after the thread ends ). Cocoa calls the set of counters that maintain all applied memory as a pool. When the pool is no longer needed, it needs to be drain ).

What I want to say is that although the iPhone supports autorelease, we 'd better not use it. Because the autorelease mode is essentially a mechanism to delay memory release, and the cell phone space is limited, we must save memory and ensure that unnecessary memory should be quickly released, otherwise, it may overflow when your program uses a lot of memory. This habit should be developed from learning to use objective-C. Otherwise, using autorelease for a long time will make you "lazy". In case of problems, it takes a lot of time to solve the problem. Therefore, we are still doing our best to manage the memory. Of course, I don't mean I can never use it. Instead, when using autorelease can significantly reduce Program Complexity and ease of use, I should consider using it for another taste.

Speaking of this, some people may have begun to get dizzy and think this is hard to understand. Yes. Here I will only introduce a rough introduction. Here I only need to understand the concept of counters. I will discuss this function in detail in the subsequent chapters, please rest assured that this is as simple as Hello world.

About pool

When using the pool, remember that the pool capacity provided by the system is not infinitely large. From this point, it is similar to the real-world credit card.

You can make an overdraft to a certain extent, but if you forget the credit card quota, it will cause great system risks.

The third is the traditional and original C language. I will not describe it here. Unless you use C code in objective-C, do not use C to apply for and release the memory, which will increase the complexity of the program.

What is a thread?

A thread refers to a single sequence of control flow in a process. It is the basic unit for Independent System Scheduling and dispatching. Multiple threads in the same process will share all system resources in the process, such as file descriptors and signal processing. A process can have multiple threads, and each thread executes different tasks in parallel.

2.5. About [[NSAID utoreleasepool alloc] init];

I will introduce the arc and the content in the arc on the right side of the equal sign of line 1 of the program in subsequent chapters. Here, the students can understand that by telling the objective-C compiler [[nutoreleasepool alloc] init], the compiler will successfully compile and generate the nutoreleasepoo object code.

2.6. Comments in objective-C

The comments of // are displayed in Row 3. The comments are the same as those of C ++ and Java, indicating that the content of this line is comments and the compiler will ignore the content of this line. I have mentioned above that objective-C is fully compatible with C language, so the traditional/**/in C language is also effective in objective-C.

2.7, command line output

Row 3 shows the nslog function. As we have already mentioned in NS, we all know what log means. This code is used to output a string. The xcode code generator defines the string as "Hello, world !". Nslog is equivalent to printf in the C language. Because we are using objective-C, I will join my classmates and forget the printf we used to be familiar.

With a sharp eye, you will find that there is an @ symbol in front of the string. What is this?

As mentioned above, objective-C and C are fully compatible, but the nslog function requires the nsstring parameter, which leads to a problem. If the string method of C is used, to maintain compatibility with C, the compiler will understand the string as a C string. To draw a line between the string and the string of C, add the @ symbol before the string of C. The objective-C compiler will think that this is an nsstring and is a parameter that nslog prefers.

Why does nslog or cocoa like nsstring? Because nsstring encapsulates a series of string methods, such as string comparison, conversion between strings and numbers, it is much easier to use than C strings.

2.8. Summary in this Chapter

Thank you for your patience!

By understanding the content of this chapter, you should be able to use xcode to create a command line project. the basic elements of M files, the idea of understanding the memory management method, the Comment Writing of objective-C, and the command line output method.

Is it simple and fun? I will try my best to make it easier to explain complicated things, and I sincerely hope you can enjoy them.

In the next chapter, we will explain a concept that students are already familiar with. Class is also a class.

Related Article

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.