10 Cocoa & amp; Objective-c development questions confusing new users in IOS development (43)

Source: Internet
Author: User

First of all, please understand that I may use a lot of English. After all, English documents will be your main source of information in the future.

This blog will describe the problems and obstacles that many Cocoa developers have encountered. Before you continue to learn more about MacOS programming, please stop and find out these problems. If you are a newbie, please do not want this tutorial to be very thorough at a time. If you want to learn more, you will have a new experience.


1. language background
First, the c and c ++ background is required. Many people ask, "I don't want to learn objective-c directly because I don't have any language basics. "Here is a few simple words: objc is the superset of c, that is to say, most of the objc code is actually c, and many open-source code is written in c and c ++. You cannot learn c well. You can only be a second-stream developer in the unix world! It may be too harsh, but I think about it myself.

Next, English is required. Apple does not write all their documents into Chinese. "What, someone translate ?" When someone is busy translating it out, everyone has sold a lot of software. You are also following people's ass for development.


2. runtime (runtime)
Objective-c is a dynamic language, and many new users or developers are often confused by runtime. This is a very important concept. I can ask, "how do you start to implement a computer language ?" Few Programmers think that way. However, such a question will force you to think about the previous question at a higher level. Note that the key to the design is implementation.

I divide the implementation into three different layers:

The first type is traditional process-oriented language development, such as C language. Implementing the C language compiler is simple. You only need to implement an LALR syntax analyzer according to the syntax rules. Compiler optimization is a very difficult topic. It is not discussed here and ignored. Here we have implemented one of the most basic and original goals of the compiler is to convert the function name in the code into a relative memory address, convert the statement that calls this function into a jmp jump command. When the program starts running, the call statement can jump to the corresponding function address correctly. This is good and straightforward, but it is too rigid. Everything is predetermined.

We hope the language is more flexible, so we have the second improvement to develop object-oriented languages, such as c ++. C ++ adds the class part based on c. But what exactly does this mean? How should we consider the compiler for writing it again? In fact, it is to let the compiler turn around and add a class processing mechanism to the strict c compiler to limit a function to the class environment in which it is located, each time you request a function call, find its object, its type, return value, parameters, and so on. After determining these, jmp jumps to the required function. In this way, many programs increase flexibility. Similarly, a function call will return completely different results based on the Request Parameters and the class environment. After adding the class mechanism, it simulates the abstract pattern of the real world. Different objects have different attributes and methods. In the same way, different classes have different behaviors! Here we can see what further thinking has been made as a compiler developer. Although the face object language has been improved, it is still rigid. We still call c ++ static language.

Hope to be more flexible! So we completely abstracted the implementation part of the above class into a complete runtime detection environment, forming the third Dynamic Language. This time, write the compiler and even retain the sytax name, name error detection, and runtime environment registration of global classes, functions, variables, and so on, we can add the necessary functions for this layer infinitely. When calling a function, the system detects the possible parameters in the runtime environment and then performs a jmp jump. This is the runtime. The compiler is more curved than above. However, this layer greatly increases program flexibility. For example, when calling a function in the first two languages, it is very likely that a jmp has an Invalid Address that causes the program crash. However, in this layer, runtime filters out these possibilities. That's why dynamic langauge is stronger. Because the compiler and runtime environment developers have already helped you solve these problems.

So many statements are mentioned above. Let's look at these statements in objective-c:

 
Id obj = self; if ([obj respondsToSelector: @ selector (function1 :)) {} if ([obj isKindOfClass: [NSArray class]) {} if ([obj conformsToProtocol: @ protocol (myProtocol)]) {} if ([[obj class] isSubclassOfClass: [NSArray class]) {} [obj someNonExistFunction];

A seemingly simple statement, but in order to enable the language to implement this capability, the language developer has to make a lot of efforts to implement the runtime environment. The runtime environment handles checks for weak types and functions. Runtime checks whether the corresponding functions and types exist in the registration list, determines the correct function address, and then saves the register status, presses the stack, and CALLS functions.

 
Id knife = [Knife grateKnife]; NSArray * monsterList = [NSArray array]; [monsterList makeObjectsPerformSelector: @ selector (killMonster :) withObject: knife];

It is quite difficult to use c and c ++ to complete this function, but dynamic language processing is very simple and these statements make the objc language more intuitive.

In Objc, function calls for objects are no longer common function calls. [obj function1With: var1]; such function calls are converted to objc_msgSend (target, @ selector (function1With :), var1 );. The runtime environment of Objc is open-source, so we can give a brief introduction to the implementation. We can see that objc_msgSend is implemented by the assembly language, and we don't even need to read the code. We only need to view the comments to understand it, the runtime environment performs a comprehensive security check before calling the function. It is ensured that dynamic language function calls do not cause crash. If you want to learn more, you can download the Objc-runtime source code to read it.
 
/*************************************** * **************************** Id objc_msgSend (id self, * SEL op ,*...) ** On entry: a1 is the message sender er, * a2 is the selector *********************************** * ******************************/ENTRY objc_msgSend # check whether receiver is nil teq a1, #0 moveq a2, #0 bxeq lr # save registers and load into ER's class for CacheLookup into FD sp !, {A4, v1-v3} ldr v1, [a1, # ISA] # explorer is non-nil: search the cache CacheLookup a2, LMsgSendCacheMiss # cache hit (imp in ip) -prep for forwarding, restore registers and call teq v1, v1/* set nonstret (eq) */ldmfd sp !, {A4, v1-v3} bx ip # cache miss: go search the method lists LMsgSendCacheMiss: ldmfd sp !, {A4, v1-v3} B _ objc_msgSend_uncached LMsgSendExit: END_ENTRY objc_msgSend. text. align 2 _ objc_msgSend_uncached: # Push stack frame ready FD sp !, {A1-a4, r7, lr} add r7, sp, #16 SAVE_VFP # Load class and selector ldr a1, [a1, # ISA]/* class = receiver-> isa */# MOVE a2, a2/* selector already in a2 */# Do the lookup MI_CALL_EXTERNAL (_ class_lookupMethodAndLoadCache) MOVE ip, a1 # Prep for forwarding, Pop stack frame and call imp teq v1, v1/* set nonstret (eq) */RESTORE_VFP ldmfd sp !, {A1-a4, r7, lr} bx ip

Now let's talk about the negative impact of runtime:

1. execution efficiency issues. "Static language execution efficiency is higher than Dynamic Language execution efficiency. Because some cpu computing losses are in the runtime process, from the assembly code above, we can also see where the loss is. The machine commands generated by static languages are more concise. Because of this, developers have made a lot of effort to keep the runtime small. Therefore, objecitve-c is a super set of c + a small runtime environment. However, in other words, from an algorithm perspective, this complexity is not different, and the Big O notation results will not be different. (It's not log (n) vs n2)

2. The other is security. Due to the runtime environment requirements, the dynamic language retains some source code-level program structures. This will facilitate the cracking. A ready-made instruction is that java, as we all know, runs on jre. This is a typical example of runtime. All of its execution files. class can be decompiled back to approximate source code. Therefore, the additional prompt here is that if you need to write security-related code, use c directly if you are away from objc.

Easy to understand: "Runtime is everything between your each function call ."

But you need to understand that the second point I mentioned is not just because runtime brings these simple language features. However, these simple language features require you to consider and solve problems from different perspectives in actual use. Computing is only 1 + 1. Many languages are the same, but with the complexity of the problem and the growth of projects, static and dynamic languages will produce completely different scenery.


3. thread
"Thread synchronization another notorious trouble !"

Remember to take the Operating System Course at school. There will be a special chapter on task scheduling and producer and consumer issues. This lays the foundation for future process and thread development. The concept is simple, but the difficulty lies in synchronization, because the Deadlock Detection Algorithm is not 100% effective, otherwise there is no deadlock. Another reason is that such errors are often obscure, and static analysis is hard to find. At the same time, a high degree of abstraction for multi-threaded development requires experience to grasp.

 

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.