Effective OC2.0 52 Reading notes (II)

Source: Internet
Author: User

Chapter II: Objects, messages, run-time

6 Understanding the concept of attributes

Summary: OC solves the problem of hard-coded offsets, one scenario is to treat instance variables as a special variable for storing offsets, to be held by class objects, and offsets to be found at run time, called robust "application binary interface" ABI. Two scenarios are accessing instance variables using Access methods. The access method for a property is performed by the compiler at compile time, and the compiler automatically adds an instance variable to the class.

Eg: if you inherit a subclass from the Nsmanagedobject class in the framework of core data, you need to dynamically create an access method at run time. Because some properties of a subclass are not instance variables, their data is from the back-end database.

@interface Eocperson:nsmanagedobject

@property NSString *firstname;

@property NSString *lastname;

@end

@implementation Eocperson

@dynamic The firstname,lastname;//compiler does not automatically synthesize access methods or instance variables at this time.

@end

Attribute traits can be divided into four classes, atomicity, read/write permissions, memory management semantics (as long as the object used to implement the property is mutable, it should be copied when setting a new property value) method name @property (Nonatomic,getter=ison) BOOL on;

When implementing a custom initialization method, be sure to follow the "copy" semantics declared in the attribute definition, _first = [firstName copy], and use the other memory management semantics.

Note: The access method should not be called in the Init method, and immutable objects should be used whenever possible.

7 Accessing instance variables directly inside the object as much as possible

Summary: It is recommended to use the direct Access form when reading instance variables, and to do so by attributes when setting instance variables.

The two approaches differ: direct access to instance variables is fast, and the code generated by the compiler accesses the memory that holds the object instance variable directly. However, the memory management semantics defined for the related property are bypassed. Key-value observations are not triggered. Using property access helps you troubleshoot related errors.

When writing to an instance variable by setting a method, it is important to note that the instance variable should be accessed directly in the initialization method and in the Dealloc method, for the initialization method because the subclass may have a replication setting method. In the default initialization method of the base class, the last name may be set to an empty string. If this is done by setting the method, then the call will be a subclass of the Set method, which throws an exception.

-(void) Setlastname: (NSString *) lastName

{

if (![ LastName isequaltostring:@ "Smith"]) {

[NSException raise:nsinvalidargumentexception format:@ "Last name must is Smith"];

}

Self.lastname = LastName;

}

Also: When you want to initialize lazily, you must access the property by getting the method, otherwise the instance variable will never be initialized.

8 Understanding the concept of "object equivalence"

Summary: Two key methods for judging equivalence:-(BOOL) IsEqual: (ID) object; -(Nsuinteger) hash; When you write a hash method, you should experiment with the current object to choose between reducing the frequency of collisions and reducing the complexity of the operation. Sometimes judgment equivalence can be based on a unique identifier, just like a primary key. Objects placed in the container should not be changed, such as putting an object into a set and then modifying its contents, then the subsequent behavior will be difficult to anticipate. The same object must have the same hash code, but the two hashes of the same object may not be the same. Do not blindly test each property individually, but should be based on the specific requirements to develop a detection plan. When you write a hash method, you should use an algorithm that is fast and has a low probability of collision with the hash code.

9 Hiding implementation details in class family mode

Summary: The class family pattern can hide implementation details behind a set of simple public interfaces. Factory mode is one way to create a class family. Most of the collection classes in the Cocoa System framework are class families. For example, when an instance is obtained using the Nsarray Alloc method, the method first assigns an instance of a class that acts as a placeholder array. The array is later converted to an instance of another class, and that class is the entity subclass of Nsarray. When new entity subclasses are added to the class family, for employee This example, without the source code of the factory method, the employee category cannot be added to it. However, for nsarray such a class, there is still a way to increase the subclass, but from the class family of public abstract accumulation of inheriting subclasses should be careful, if there is a development document, should read first.

10 using associated objects to store custom data in existing classes

Summary: Sometimes it is necessary to store relevant information in an object, but an instance of that class may be created by a mechanism, and we cannot allow this mechanism to create a subclass instance of its own abbreviation. It is necessary to solve this problem with the associated object (associated objects). Objc_setassociatedobject (object,void *key,id value,objc_associationpolicy), Objc_getassociatedobject (Object,key), Objc_removeassociatedobjects (object). Similar to Nsdictionary, the key used to set the associated object is an opaque pointer (opaque pointer), and if the return value of the IsEqual method called on two keys is yes, then Nsdictionary considers this. Then, when setting up the associated object, if you want to match two keys to the same value, the two must be exactly the same pointer. So when you set the associated object value, you typically use a static global variable to do the key. Associate objects should be selected only when other practices are not available, because this practice often introduces bugs that are difficult to find.

11 Understanding the role of objc_msgsend

Summary: Boundary condition (special case), OBJC_MSGSEND_STRET returns structure, Objc_msgsend_fpret returns floating point number, objc_msgsendsuper. Tail call Optimization Technique: If the last operation of a function is to invoke another function without returning its value to another, it can perform a "tail call optimization". Only the call record of the inner function is preserved, and if all functions are tail-called, then it is possible to make only one entry for each execution of the call record, which will greatly save memory. The message consists of the receiver, the selection sub, and the parameters. Sending a message to an object is equivalent to calling a method on that object. All messages sent to an object are handled by a dynamic messaging system that detects the corresponding method and executes its code.

12 Understanding Message Forwarding mechanisms

Summary: Message forwarding is divided into two stages, a dynamic method analysis: First consult the receiver, the class, to see if the dynamic method can be added, two complete message forwarding mechanism: First see if there are other objects can handle this message. If not, the full message forwarding mechanism is initiated, and the runtime system encapsulates all the details related to the message into the Nsinvocation object.

+ (BOOL) Resolveinstancemethod: (SEL) selector; (not yet implemented is an instance method call this method)

+ (BOOL) Resolveclassmethod: (SEL) selector; (The class method is not yet implemented)

Implement @dynamic Property with + (BOOL) Resolveinstancemethod: (SEL) Selector

Return yes, or return [Super Resovleinstancemethod:selector]; dynamic Add method

-(ID) Forwardingtargetforselector: (SEL) selector; You can simulate some of the features of multiple inheritance, but you cannot manipulate the messages that are forwarded by this step.

-(void) Forwardinvocation: (nsinvocation*) invocation; one is to change the invocation target, but it is equivalent to the previous effect. Second, before the departure message, first change the message content in some way, append another parameter, or switch the selector.

Calayer is a container class that is compatible with key-value encodings, which means that you can add properties to the inside arbitrarily and then access them as key-value pairs. The storage of property values is directly responsible for the base class, and we only need to define the new attributes in the Calayer subclass.

If the object cannot respond to a selector, it enters the message forwarding process. With the dynamic method parsing function at run time, we can add it to the class when we need to use a method. objects can transfer certain selectors that they cannot interpret to other objects for processing. After these two steps, if there is still no way to handle the selection, then start the full message forwarding mechanism.

13 using method to adjust black box method

Summary: The method of Exchange is used void Method_exchangeimplementations (method M1,method m2); methods Class_getinstancemethod (Class AClass, SEL aselector). With this scheme, it is helpful to debug the program by adding the logging function to the black box method which is completely unaware of its implementation. Misuse, however, makes the code difficult to read and difficult to maintain.

14 Understanding the purpose of class objects

Summary: In the program do not directly compare the class to which the object belongs, it is wise to call type information Query method, Iskindofclass and Ismemberofclass, can also be used to compare class object is the same way to do. If so, use the = = operator and do not use isequal because the class object is simple interest, and within the scope of the application, there is only one instance of class. Each class has only one class object, so you can use = =, and each class object has only one meta class associated with it. Try to use the type information query method to determine the object type, rather than directly comparing the object, because some objects may implement the message forwarding function, if the object returned by the method class directly compared with the found class object is different, the class method returns the object that represents the initiating agent, Instead of accepting the proxy object.

Effective OC2.0 52 Reading notes (II)

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.