Objective-C notes worth the attention of programmers

Source: Internet
Author: User
Some points worth attention in objective-C: 1. there are the following aspects about bool traps: it is best to compare bool condition statements with the no value, because bool's yes and no values are only agreed, in addition, the compiler recognizes bool as an 8-bit binary data. If you accidentally assign an integer value greater than 1 byte to the bool variable, only the base byte will be used as the bool value. If the base byte is exactly 0, the bool value is 0, that is, the NO value. Therefore, we recommend that you compare the variable value with the no value for comparison. 2. some basic Syntax problems in objective-C: (important statement: Objective-C is C, not any other language) ns *** naming rules: in short, it is to add the Hungarian naming method with ns as the prefix. # Usage of import in objective-C: # the usage of import in objective-C is equivalent to # include in C/C ++, however, the former is different from the latter in terms of functions. To put it simply, the former ensures that the header file is only contained once, regardless of the actual usage of this command in that file) the number of times. In C language, programmers usually use the opportunity # ifdef command to avoid the situation where one file contains another file, and the latter contains the first file. In objective-C, programmers use # import to implement this function. Usage of nslog () and @ "string" in objective-C: The function of nslog () in objective-C is equivalent to console, printf () in C/C ++. Nslog () also has some functions not available in console and printf (), such as timestamp, date stamp, and automatic addition of line breaks ('\ n. In objective-C, the @ symbol is one of the features added on the basis of the standard C language. "" There is a @ symbol before the string in double quotation marks, this indicates that the referenced string should be processed as the nsstring element of cocoa. Some functions of nsstring include: A. Tell the length; B. Compare itself with other strings; C. convert itself to an integer or floating point value. A Brief Introduction to multi-parameter methods in objective-C: One thing that needs to be captured for multi-parameter methods is that the names of subsequent parameters must be written. In objective-C, add signs, minus signs, and brackets. Their meanings and usage: first, we need to understand that there is no concept of public and private in objective-C, it can be considered that all are public. Subtraction indicates the beginning of a function, method, or message. The plus sign indicates that you do not need to create a class instance. Other classes can directly call functions in this class (or the plus sign indicates static member functions ). Brackets in objective-C indicate the call of a method (usually "message" in objective-C "). The following conversion relationship can clearly understand the use of brackets: [[[mycalss alloc] init: [Foo bar] autorelease]; it is converted to C # or Java syntax such as mycalss. alloc (). init (FOO. bar ()). autorelease (); this conversion relationship is very important. Last, I would like to introduce some important things and some problems: 1.id: objective-C has a special data type: ID, which can be understood as "casual ". It is equivalent to void * in C language. In objective-C, all data is saved as pointers. What you get is the location of the object in the memory, and ID is the location you know. 2. different objects can be saved in the same array: different objects can be saved in the array (nsarray) in objective-C, which is represented by the following example: {myarray <-| 0 :( float) 234.33f 1: @ "play entertainment" 2 :( nsimage *) (image resource) 3: @ ""} the array above contains four elements: Floating Point Number, string, and image. 3. bool, yes, no: in objective-C, yes is usually equivalent to true in C #, Java, C, C ++, and no is equal to false, in fact, yes is 1, no is 0, and bool itself is a char type data (the compiler recognizes it as eight-bit binary data ). 4. what are iboutlet and ibaction? Why can we always see that iboutlet and ibaction do not play a major role in syntax? If you want to see this control object in interface builder, add (iboutlet) before the definition, and you can see the outlet object in Ib. If you want to control an object to execute certain actions in interface builder, add (ibaction) before the method ). in fact, iboutlet and ibaction are the same as void. 5. What is the meaning of Nil: NULL (null) in objective-C is represented by nil, and nil represents a null pointer. 6. what is the difference between @ "string" and "string"? "string" is a C string. @ "string" is a shorthand for converting a C string to an nsstring. this conversion is required only when nsstring is needed, for example, in nslog. the "string" format is used where the C string is required. in addition, @ "" This conversion does not support Chinese characters. For example, nslog (@ "string") cannot output Chinese characters. 3. function prototype and declaration method: first, the short-term-that is, the "minus sign", the name of each method, the type of the return value of the method, and some parameters. The first short-term followed by the return value. infix: in objective-C, there is a syntax technique named infix Natation. The method names and their parameters are all combined. for example, you can call a method with a parameter as follows: [circle setfillcolor: kredcolor]; call a method with two parameters as follows: [textthing setstringvalue: @ "Hello there" color: kbluecolor]; setstringvalue: and color: are actually the parameter names (actually part of the method name, which will be detailed later), and @ "Hello there" and bluecolor are the passed parameters. colon: A method with parameters usually ends with a colon at the end of the method name, followed by this parameter type and Its Parameter Name. the circular arc after the colon is a parameter type. in a method without parameters, the end of the method name is usually a semicolon instead of a colon. it is worth noting that sometimes it is because there is no Parameter Is followed by a colon, causing the program to have an error message is meaningless preliminary error. the following is a summary of the typical form of function prototype and Declaration:-(method type) method name: (parameter type) parameter name; or:-(method type) method Name. Finally, @ end must be added to the last sentence to indicate that the declaration of the Compiler class has been completed. this is also an important foundation. 4. instructions for implementing code and notes: the compiler provides code for a class using the @ implementation command. The class name appears after @ implementation, and there is no semicolon at the end of the line, this is because you do not need to use a semicolon after the objective-C compiler instruction. the definition of each method in the @ implementation command does not need to appear in the order in the @ interface command. You can even define methods that do not have the corresponding declaration in @ implementation. You can regard them (here they mean: there are no declared methods in @ Interface) as private methods and only use them in class implementation. Note that there is no real private method in objective-C. that is to say, the methods defined in the @ implementation command can be accessed from the outside. This is a dynamic side effect of objective-C. passing hidden parameters is another example of indirect operation. in objective-C runtime, different objects can be passed as hidden self parameters. Therefore, when instance variables of objects are changed, they can also be changed during runtime. note: When you run an application, objective-C supports the code block of the current application (including our own application) and runs very important tasks, for example, sending messages and passing parameters to an object. 5. instantiated object: The last and most critical process in shapes-object. In this process, we create shape objects, such as red circles and green rectangles, the terminology of this process is called Instantiation ). when instantiating an object, you need to allocate memory, which is then initialized and saved with some useful The default value is different from the random value you get when you get the newly allocated memory. After the memory allocation and initialization are complete, a new object instance is created. note: because the local variables of an object are specific to the instance of the object, they are called instance variables, which are usually abbreviated as ivars. to create a new object, we need to send a new message to the corresponding class. Therefore, after receiving and processing the new message, we will get a new object instance that can be used. objective-C has an excellent feature. You can use a class as an object to send messages to a class. This convenient behavior is not limited to a specific object, but is common to all classes, this type of message is usually used when creating a new object. If you need to create a new circle object, it is more appropriate to request a new object in the circle class than to request an existing circle object. 4th chapter: 1. inheritance :~~ @ Interface circle: nsobject ~~ The identifier after the colon is the class to be inherited, because the object can be inherited from a non-class. cocoa and nsobject inherit objects because nsobject provides a lot of useful features (you can also get these features when inheriting a class that has been inherited from nsovhect ). in objective-C, inheritance does not support multi-inheritance. To obtain the advantages of multi-inheritance in objective-C, you must use other features of objective-C, such as classification and protocol, chapter 12 and Chapter 13 are introduced in this book. 2. refactoring: the method of moving and simplifying code is called refactoring, which is a very fashionable topic in the OOP community. during refactoring, you can move some code to improve the program architecture, just as we delete the repeated code in the program without changing the code behavior or running results, the general development cycle includes adding some features to the code, and then deleting all repeated code through refactoring. generally, after adding some new features to an object-oriented program, the program becomes simpler. You may find it strange. This is the case after the shapes class is added. note: inheritance only applies to subclasses and superclasses. As you can see, a "is a" (a) relationship is established. Therefore, the instance variable of nsobjec is called Isa. that is, rectangle is a shape, and circle is a shape. You can use rectangle or circle to replace the shape code. replace a general shape with a more specific type of object (rectangle or circle). This capability is called polymorphism, which visually represents "many shapes" in Greek ". be careful: the compiler uses the "base address plus offset" mechanism to implement amazing functions. the base address of the given object refers to the position of the first byte of the first instance variable in the memory. by adding an offset address to this address, the compiler can find the location of other instance variables. for example, if the base address of the rounded rectangle object is 0x1000, the IP address of the ISA instance variable is 0x1000 + 0, that is, the value of ISA occupies 4 bytes, therefore, the starting address of the next instance variable fillcolor is located after four offset addresses, that is, 0x1000 + 4, or write 0x1004. Each instance variable has an offset from the base address of the object. if the fillcolor instance variable in the access method is used, the compiler generates code and obtains the Location Value for storing self, and then adds the offset value (4 in this example) to obtain the location pointing to the value of the stored variable. over time, this also produces some problems. Now, in the program generated by the compiler, these offset locations are implemented through hard encoding. although Apple engineers want to add other instance variables to nsobject, they cannot, because this will change the offset location of all instance variables. this is called fragile base class problem ). apple solved this problem by introducing a new 64-bit objective-C operation in leopard (which uses indirect addressing to determine the location of the variable. 3. rewrite method: Sometimes a new method needs to be added to introduce a unique feature in the class. it is also necessary to replace or enhance the existing methods defined by a super class of the new class. (leave a method empty. When each subclass in the method implements its own When you use a functional method, the method is rewritten.) The keywords involved include: Super (superclass ). Note: It is always a good choice to call a superclass method during method rewriting, so that more functions can be implemented. by calling super, you can obtain all the features of the method. 5th chapter: 1. what is composite: Combine multiple components to get a complete work. note that, strictly speaking, only a combination of objects can be called composite. Basic types such as int, float, Enum, and struct are considered part of objects. note: If the class does not contain human and instance variables, you can ignore curly braces in the code. Note: You can use the % @ format specifier to output objects through nslog. when nslog () processes the % @ specifier, it will ask the corresponding object in the parameter list to get the description of this object. technically, nslog () sends a description message to this object, and the description method of the object generates an nsstring and returns it. then nslog () contains this string in its output. you can add the description method to the class to customize how nslog () Outputs objects. 2. access Method: the access method is used to read or change the specific attributes of an object. The class access method is called the setter method. The other method is the getter method. The getter method provides a way to read object attributes by using the object code. 3. mutator is used to change the object state. Note: When operating on the attributes of an object, you should always use the access method provided by the object and never directly change the value of the object attribute. An access method is another example of indirect program work. 4. defense programming: Use common code in the access method to check the array index of instance variables to ensure that it is a valid value. If it is out of the valid range, then the program will output an error message and exit. This section of code is called defensive programming. (programmers need to consider various possible problems, and set the exception throw mechanism, extended to the problem of programmers empathy, it can show part of the functions to be optimized ). Note: Do not use complicated systems to inherit the modules contained in the system. For example, in simple terms, the kinship inheritance between the father and the child is unidirectional, therefore, the applicability of inheritance also needs to be considered. Chapter 7th-learn more about xcode: 1. tips and tricks for using the editor: xcode provides suggestions when developers enter the code method. This is the code prompt function of xcode, usually called the Automatic completion function of code. in xcode, the shortcut key "command" and "[" and "]" are used to shift the entire line of code at the current cursor position to the left and right. Add "/" to the Command key to annotate a line of code at the current cursor position. 2. matching parentheses: when you enter the program code, the screen may flash a bit after you enter certain characters (such as ")", "]", or, this is where xcode tells you where the square brackets are. this is xcode's "matching brackets". Alternatively, you can double-click a separator to select it and all the code between the matching brackets. 3. batch EDIT: Select File-> make snapshot (shortcut: command-control-S). xcode remembers the current status of the project. you can "Destroy" your project as you like. if you realize that you have made a very serious mistake, you can use file-> snapshots to restore your snapshot. we recommend that you back up a copy of the code and keep a copy of the current full version of the Code snapshot when making major changes to any project. (Note: The importance of the backup code, because in fact the snapshot is stored in a disk image, it is stored in ~ /Library/Application Support/developer/shared/snapshotrepository. sparseimage. sometimes this disk image may be damaged (maybe it is too stressful), and xcode will report you a "mysterious" error: Snapshot failed: A project snapshot cannot be created. if the developer sees such an error, try to delete the scene and restart it ). 4. search and replace function in xcode: this function is available in the sub-menu edit-> Find. there are several very convenient options. the find in project can be searched and replaced in all files of the project. in fact, this kind of search and replacement work is not very easy to use. For example, if a developer just wants to rename the variables in the function, so it does too many operations (because it may change the variable name in the entire file), and developers want to rename a class, it cannot do it, but also an important point, it cannot rename the source file. <There are two other functions to make up for these shortcomings: 1. it can be referred to as edit all in scope. developers can select a symbol, such as a local variable or parameter, and then select edit-> edit all in scope, all the symbols will be updated immediately when they appear. This is not only a shortcut with a large number of changes, but also looks cool. After the input, if you click somewhere else in the source file editing window, the edit all in scope mode is left. 2. "Built-in refactoring tool". If a developer has a GUI program, it can even go deep into the NIB file level for modification, set the insert point in the file to be modified, and then select refactor, to guarantee the security, make sure that the snapshot check box is selected. After you Click Preview, xcode analyzes what to do and displays the result. unfortunately, refactoring cannot rename the text in the comment. Therefore, you must manually edit the comment at the end of the class, the header file comment generated by xcode, or the comment written by any developer, developers can use the search and replacement functions to simplify this process. 5. code navigation: see the Emacs shortcut in the blog. Bytes. Enter text in the search box to filter these files. 8. open the door with sesame: If the developer is looking at a source file and sees # import at the top of the file, is it very convenient if Xu Su can open this header file without clicking the mouse? This is very easy: you only need to use the command + Shift + O key to bring up a dialog box, and then enter the header file name displayed by the developer in the search box, select an appropriate file from the information displayed below to view the file content. 9. bookmarks: In xcode, you can insert bookmarks with developers in the Code. In the code, there may be some points that need attention, such: if you need to modify, optimize, and other operations in a region of the Code, the developer can quickly locate the operation by making a mark here. The method is as follows: first place the insert point in the source file or select a text area, then select edit-> Add to bookmarks, or use the default shortcut key command + D (the same as in Safari ), at last, enter the name of the bookmarks when prompted. 10. focus: Next to two empty columns on the left of the source code, the wide column on the left is called the edge column (gutter), and the narrow column on the right is called the focus column (Focus ribbon ): the focus column enables developers to focus on code segments. grayscale of the Focus column: the deeper the code is nested, the deeper the gray will be in the focus column next to it. this color encoding can make the code more complex at a glance. when you hover over the focus column, the corresponding code segment is highlighted. You can also click the focus column to collapse the corresponding code segment. 11. enable navigation bar: Right-click a widget bar at the top of the Code Editor, that is, the navigation bar. many of the preceding controls allow developers to quickly switch between source files in the project. # pragma Description: "Pragma" is derived from the Greek word, meaning "action ". # The Pragma command passes information or instructions beyond the general code of objective-C to the editor and code editor. generally, Pragma is ignored, but it may have other meanings in some software development tools. If a tool does not know what Pragma is, it should "nod and smile" and ignore it, instead of generating warning or error messages. 12. the floating window of research assistant updates the content of the displayed content based on the interaction operation performed by xcode. To open the research assistant, choose Help> show research assistant. 13. document Management Program: developers want to directly access the official API documentation of Apple. The fastest way is to press and hold the option key and double-click a symbol, which is a shortcut for searching the documentation related to the symbol. it is easy to open documents in other xcode windows or even web browsers. You only need to press and hold the control key and click (or right-click) the document area to open the menu. 14. debugging: the process in which the system finds errors in the program in the Code is called debugging ). 15. brute-force debugging: the simplest debugging method is brute-force debugging. brute-force debugging refers to the control process and some data values of the program by placing an output statement (such as nslog) in the program. 16. xcode Debugger: xcode also has a debugger, which is located between programs written by developers and operations. It can interrupt developers' programs and stop them in operation. in this way, the data of the check program and its modification program can be moved. developers can also perform a row-by-row check without executing a single program. note: The debugger used by xcode is GDB, which is part of the GNU project and can be used on many different platforms. if the developer is willing to, he can also run it through the command line. GDB has a complete documentation system, although its documentation is difficult to understand and has several versions of GDB tutorials circulating on the Internet. 17. exquisite debugging symbols: when you plan to debug a program, make sure that the developer is using debug to generate the configuration. you can use the pop-up menu "active build configuration" in the xcode toolbar to check the configuration. the debug configuration tells the editor to issue additional debugger symbols, while the debugger uses These symbols can know where the program is written. at the same time, make sure that the program runs with the debugger. In xcode, you can choose run> run from the menu or press the shortcut key command + R, the program will not run using the debugger. To use the debugger, choose run> go (Debug), run> debug, or press the shortcut key command + Y. (multithreading programming is a programming method that processes multiple execution streams at the same time. It is very difficult to correctly apply it. Generally, the errors produced by multithreading programming are very difficult to find, if someone tells you that multithreading is easy, they are not cheated or trying to sell you something. The following describes four controls: the first control looks like the start button of the cdnserver. You can use command + Option + P to enable the security key. After you click it, the program runs to the next breakpoint, and then ends or crashes. the second control looks like the shortcut key used for skipping the button is command + Option + O. after clicking this control, it will execute the next line, and then the control of the program will be handed back to the developer. The third button points down to the arrow of a point, it is a jump button (you can also use the shortcut key: Key + command + I in the upper right corner of the keyboard). The function of this button is to jump into the method and display its code, the last arrow is set at the starting position of the Code. the fourth button is the jump button. The shortcut key is command + key + T in the upper-right corner. Clicking it will terminate the currently running function and the program will stop in the next line of code of the calling program. in the test, there is no need to press this key in the test. The next button (the box of another spray can) is used to open the xcode debugging window, And the next button is used to open the GDB Console. developers can directly enter Debugging commands using this debugger. the last control displays the pop-up menu of the Call Stack. The call stack is a set of currently active functions. If a calls B and B calls C, C is at the top of the stack. in more complex programs, such call stacks are also called Stack tracing. 18. check Program: When a developer sets a breakpoint or step-by-step execution in a certain part of the program, it indicates that the developer understands the program status-variable value. in xcode, the data prompt function is available. chapter 8-quick tutorial on foundation kit: the cocoa framework consists of two different frameworks: Foundation kit and Application Kit, which contain all user interface objects and advanced classes. the main () function is created through alloc and initialized through init1. useful data types:. scope, B. geometric data type. A. the first struct is the nsange, the first is to directly assign values to the self-segment, the second is to apply the Aggregation Structure assignment mechanism of the C language, and the third is the shortcut function nsmakerange () provided by cocoa; for example: x. nsange range; range = 17; range = 4; Y. nsange range = {17,4}; Z. nsange range = nsmakerange (13, 15); B. nspoint indicates a vertex, and nssize stores the length and width. cocoa provides a rectangle function data type composed of vertices and sizes. Its shortcut functions include nsmakepoint (), nsmakesize (), and nsmakerect: what data types of cocoa are C's struct type rather than objects? The reason is the performance. Programs (especially GUI programs) use a lot of temporary points, sizes, and rectangles to complete their work. Remember, all objective-C objects are dynamically allocated, dynamic Allocation is a costly operation, which consumes a lot of time. Therefore, creating these structures as first-level objects will increase the system overhead during the use process. 2. string: There are many built-in methods for nsstring in cocoa, which makes processing edges of strings much simpler. a. create a string and output the result nsstring and stringwithformat by accepting the format string and some parameters. The method is to create nsstring by using the format string and parameters; B. class method; C. about size, D. comparison policy, E. case-insensitive comparison, F. whether the string contains other strings. 4. dictionary nsdictionary: a dictionary is a set of keywords and their definitions. Cocoa has a collection class nsdictionary. nsdictionary that implements this function. It stores a value (which can be any type of object) under a given keyword (usually an nsstring ). Then the developer can use this keyword to find the corresponding value. Therefore, the developer has an nsdictionary that stores all the contact information of a person. then the developer can say to this dictionary, "give the value under the home-address keyword", meaning: Dictionary (also called a hash or associated array) the key query optimization storage method is used. It can immediately find the data to be queried, without facilitating the entire array for search. For frequent queries and large datasets, the dictionary is much faster than the array. In fact, the dictionary is very fast.
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.