Objective-C basic concepts and keywords

Source: Internet
Author: User

Keyword @ when we see this keyword, we should think that this is an extension of the C language for Object-C, such as @ interface XXX. @ Interface declaration class @ Implementation implementation class @ protocol declaration Protocol @ optional and @ protocol are used together, which means that one or more methods in the protocol can be used together with @ required and @ protocol, it indicates that a method or several methods in the Protocol must be implemented with @ end and @ interface, @ implementation, and @ protocol, which indicates that the declaration or implementation is completed with @ encode as the compiler macro, it can convert the type to the corresponding string. ID

ID is a pointer to an objective-C class object. It can be declared as a pointer to any class object. When ID is used in objective-C, the compiler assumes that you know, id indicates the object of the class. Unlike void *, the void * compiler does not know or assume that it points to any type of pointer.

Nil is defined as a constant. If the value of a pointer is nil, it means that the pointer does not point to any object. Self

In objective-C, the keyword self is the same as this in C ++, that is, the address of the class object itself. Through self, you can call your instance variables and methods.

Super when the subclass needs to call the method of the parent class, the super keyword is used. super points to the pointer of the parent class. It is a good habit to call the method of the parent class when the subclass overrides the method of the parent class. Because when we do not know the functions implemented by the parent class in this method, if we do not call the method of the parent class, the method we override may lose this function, this is something we don't want to see.

Nsnull

Nsnull is meaningless. If the value of a dictionary is nsnull, the key corresponding to the value has no value. For example, if the key is address, it indicates that the value corresponding to address is none.

Self super class public protected private ID

[Self class] [super class] Selector

Objective-C Runtime reference

Standard usage

Self = [Super init]

New1 objective-C has a feature that uses classes as objects to send messages. This is usually used when a new object is created, such as xxx * object = [xxx new]. class Method + If You Want To declare a method that belongs to a class but not a class object, use +. + The class method used to modify the class. The + class method is the method of the entire class and does not belong to any class object, this is the same as the concept of static in the class in C ++. In nslog, % @ indicates the description method of the object to be called. A conceptual class is a structure that represents the object type. Like int and char, it can also declare class variables (object) to be instantiated as class objects and allocate memory and initialization, this class object can be used.

Product message after object (Instance) Class instantiation

In object-C, the operations performed by class objects are implemented by sending messages to the class or such objects, for example, [object func]; that is, sending func messages to the object, similar to method calls in C ++. After a func message is sent to the object, the func method of the class of the object query is executed.

How is this method called when a message (call method) is sent to an object during method scheduling? This depends on the method height program. The method of searching for the method scheduler is as follows: Find the called method in the method of this class. If yes, call it, if the method cannot be found along the inheritance path and the class from which it is found, the method of the class will be called. If the class at the root is still not found, the compilation will fail. Inheritance and Combination Support inheritance in objective-C, but only supports a single inheritance (with only one parent class). If you want to use the multi-inheritance feature, you can use classification and protocol technologies. The inheritance is-a, and the combination is has-. Composite is implemented by containing pointers to objects. in a strict sense, composite is intended for objects and is considered part of objects for basic data types. Since nsarray, nsdirectory, and other classes cannot directly store basic data types, to use basic data types in nsarray/nsdirectory, you must use packing and unboxing. In objective-C, nsnumber and nsvalue can be used to package data types. nsnumber can package basic data types, and nsvalue can package any data types. Encapsulate the basic type into an object called packing, and extract the basic type from the encapsulated object called unpacking (unboxing). other languages such as Java Native support packing and unpacking, ojbective-C does not support automatic packing and unpacking. You need to implement packing and unpacking on your own. When using the instance variables (member data) of the Class Object, do not directly use the instance in the object. You must use the Save method to obtain or modify the instance, either setter or getter, in cocoa, there is a naming convention for access methods. We have to comply with this habit so that we can work with other team members. The setter method is to modify or set the Instance value. The naming convention is set + Instance name. For example, if a class has a path instance variable, the setter name is setpath and the getter name is path, the reason is not getpath, because get has a special meaning in cocoa. This meaning is that the get method means that the method returns the value through the form parameter pointer (passed in the function parameter pointer. We need to follow this naming convention or rule. In objective-C 2.0, @ property and @ synthesize are added to replace setter and getter. These two keywords are compiler commands. Also, the dot expression can be used to access the value of a class member. Object. Attribute. When the dot expression is on the left of the = sign, the setter method is called. When the dot expression is on the right of the = sign, the getter method is called. @ Property Syntax: @ property (parameter) type variable name. the parameters are described here. there are three types of parameters: the first type: read/write attributes (readonly/readwrite/) and the second type: setter attributes (assign, copy, retain). Assign is a simple assignment, copy is to release the old member variables, allocate a new memory address to the member variables, and copy the input parameters to the member variables. Retain adds the input parameter reference count to 1, releases the original member variable, and points the member variable to the input parameter. Third: it is related to multithreading (atomic, nonatomic). When multithreading is used, atomic is used, and nonatomic is used when multithreading is not used.

There are two methods for object creation and initialization to create an object in objective-C: [Class New]; [class alloc] init]. these two methods are equivalent, but by convention, the [[class alloc] init]; alloc operation is used to allocate memory space for the object and initialize the data members of the object, int is 0, bool is no, float is 0.0, and so on. Initialization: the default initialization function is INIT, And the init return value is ID. Why does it return ID? To implement a chained expression, nested call is called in objective-C. Why is nested call required ?? Because the init return value of the initialization method may not be the same as the object returned by alloc? Why is this happening? Initialization based on class clusters. Because init can accept parameters, it is possible to return different types of objects based on different parameters within init, so the above situation will most happen. During initialization, we recommend that you use if (Self = [Super init]) to facilitate initialization. When a class needs to initialize data members according to different situations, you need to facilitate the initialization function, different from init initialization, convenient initialization functions have parameters. The number of parameters can be 1 to n, and N is the number of class data members. Specify the initialization function: What is the initialization function? In the class, an initialization function is specified as the specified initialization function. It is determined that the rule for the specified initialization function is in the initialization function, and the most parameter is the specified initialization function, other initialization functions that are not specified as initialization functions must call the specified initialization function. The same applies to subclasses of this class. You only need to override or directly use the specified initialization function of the parent class. Here is an example of the above text. @ interface a {int X; int y ;}- (ID) Init;-(ID) initwithx :( INT) xvalue;-(ID) initwithy :( INT) yvalue;-(ID) initwithxy :( INT) xvalue yval :( INT) yvalue; @ end here initwithxy is determined as the specified initialization function. -(ID) initwithxy :( INT) xvalueyval :( INT) yvalue {If (Self = [Super init]) {x = xvalue; y = yvalue;} return self ;} -(ID) Init {If (Self = self initwithxy: 10 yval: 20) {} return self ;}....... @ interface B: A {int Z;}-(JD) initwithxy ......; @ end @ implementation B

-(ID) initwithxy :( INT) xvalueyval :( INT) yvalue {If (Self = [Super initwithxy: 10 yval = 20]) {z = 40;} return self ;}@ end

The memory management of the automatic release pool is the top priority in software code. The memory management directly affects the stability of the software. In cocoa, there is an automatic release pool, which is similar to the smart pointer in C ++. An nsobject method is autorelease. When an object calls this method, it will put this object into the Auto Release pool. Drain, which is used to clear the automatically released pool instead of destroying it. The drain method is only applicable to Mac OS X 10.4 and later versions. We need to use release in the code we write, and release applies to all versions. The automatic release pool is implemented by means of stacks. When creating an automatic release pool A, A is pushed to the top of the stack. At this time, the object connected to the autorelease message is put into the automatic release pool, at this time, a new B is created to automatically release the pool, B is pushed to the top of the stack, and B is deleted after creation. The object that receives the autorelease message still exists because a Automatically releases the pool. Reference count each object has a corresponding integer called reference count. When the reference count is 0, objective-C automatically sends dealloc to the object, the methods (messages) related to the reference count include the following 1 to increase the reference count: when an object is created through alloc, new, and copy, the reference count of this object plus 1 (actually 1, because it was previously 0) 2 Add reference count: retain3 reduce reference count: Release local allocation memory (temporary object ): 1. If you use alloc, new, and copy to create an object, you must call the release method of the object. 2. If you use non-alloc, new, or copy to create an object, the reference count of this object is 1, and has been added to the Auto Release pool. We do not need to call the release method of the object. Owner object (which exists as a member in the class): 1 if you use alloc, new, and copy to create an object, you need to release the object in the dealloc method. 2 if you use non-alloc, new, copy: creates an object. When the object is owned, the object is retained (the retain method is executed) and the object is released in the dealloc method. Dealloc when the object reference count is 0, objective-C will automatically send the dealloc message of the object (the dealloc method of the object is automatically called, similar to the C ++ destructor ), therefore, we can rewrite the dealloc method to release other resources in the class. Note: Do not call the dealloc method directly in the code.
The garbage collection mechanism (Automatic Memory Management) is introduced in objective-C 2.0 ), set objective-C garbage collection to required [-fobjc-GC-only] in the project settings to use the garbage collection mechanism. After the garbage collection mechanism is enabled, the common memory management commands are empty operation commands and no operation is executed. Objective-C's garbage collection mechanism is an inherited garbage collector. The Garbage Collector regularly checks variables and objects and pointers between them. When it finds that no variables direct to objects, this object is treated as the discarded garbage. Therefore, when an object is not used, the pointer is set to nil, and the garbage collector cleans up the object. Note: If you develop an iPhone, you cannot use garbage collection. When writing iphone software, Apple recommends that you do not use the autorelease method in your code, and do not use the function that creates an automatically released object. What is category? Category is a way to add a new method to an existing class. Why is category used or the purpose of category used? There are three points: first, class implementation can be dispersed into multiple different files or multiple different frameworks. If a class needs to implement many methods, we can classify the methods and classify the classes to effectively manage and control the code. Second, create a forward reference to a private method. Third, add informal protocols to objects. Delegated delegation means you want to do something yourself, you don't do it yourself, and you delegate it to others. In Ojbective-C, delegation is implemented through a category (or informal Protocol) or protocol. For example, Apple wants to produce an iPhone, while Apple does not (one of the reasons is that production costs are low in China and they make more money). Apple commissioned Foxconn to produce the iPhone, foxconn had to add a production line (category and method for iPhone production) for itself because it was not producing the iPhone. This is to delegate the production by category. The following code is used to illustrate this example ...... Apple * Apple = [[Apple alloc] init]; Foxconn * Fox = [[Foxconn alloc] init]; [Apple setdelegate: Fox]; [Apple produceiphone]; @ implementation apple -(...) setdelegate :( ID) X {delegate = x ;//! Specify the delegated production object as x}-(...) produceiphone {[Delegate produceiphone]; //! Authorized object production iPhone} @ interface Foxconn: nsobject... @ end @ interface nsobject (produceiphone )//! Other products can be produced before Foxconn, and have been declared and defined-(...) produceiphone //! Increase iPhone production capability @ end @ implementation nsobject (produceiphone )//! Produce iPhone-(...) produceiphone {...} @ end informal protocol to create a nsobject category, called creating an informal protocol. Why is it informal agreement? That is to say, it can be implemented, or it cannot be delegated. Taking the above example as an example, Apple requires that Foxconn not only be able to produce the iPhone, but also be completed within a certain period of time. since the two parties did not sign the contract, both the time requirement and the production requirement specifications are informal protocol selector which is the name of a method. Selector is the encoding method used when objective-C is run to achieve quick search. You can use the @ selector pre-compile command to obtain the selector @ selector (method name ). Nsobject provides the respondstoselector: method to access whether the object has this method (response to this message ). Take the above apple and ask Foxconn to produce the iPhone as an example. How does apple know if Foxconn is capable of producing the iPhone? Apple then asks Foxconn through the respondstoselector method to determine whether the iPhone can be produced (whether it can respond to the produceiphone). If the result is yes, Apple will entrust Foxconn for production, foxconn has produced a favorite iPhone product. In comparison with informal protocols, all methods specified in formal protocols must be implemented in Ojbective-C. In the Ojbective-C2.0, Apple adds two more keywords, the method in the protocol can not be fully implemented, which keywords see the keyword part of @ optional, @ required. The formal agreement declaration is as follows: @ protocol XXX-(...) func1;-(...) func2; @ end Protocol: @ interface object: nsobject <XXX> //! The object is derived from nsobject and complies with the xxx protocol. The func1 and func2 functions must be implemented .... @ End: used to allocate memory and initialize self = [Super init];
Objects interact in objective-C, and all objects interact through pointers. Fast enumeration for (type * P in array) Note: Objective-C does not support multi-inheritance this article is transferred from http://blog.csdn.net/ithero_zhou/article/details/7079031

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.