6. Understanding the concept of attributes
You can use the @property syntax to define the data that is encapsulated in the object.
Specify the correct semantics for storing data through "traits".
When setting an instance variable corresponding to a property, be sure to follow the semantics declared by that property.
You should use the Nonatomic property when developing an iOS program because the atomic property can severely affect performance.
7. Try to access instance variables directly inside the object
Two ways to access instance variables inside an object are through property access and direct access.
There is a difference between the two ways:
Because you do not go through the Object-c "method Dispatch" step, it is of course faster to access the instance variables directly. In this case, the code generated by the compiler accesses the block of memory that holds the object instance variable directly.
When you access an instance variable directly, its "set method" is not called, bypassing the memory management semantics defined for the related property. For example, if you directly access a property declared as copy under ARC, the property is not copied, only the new value is preserved and the old value is freed.
If the instance variable is accessed directly, then the "key-value observation" (Key-value OBSERVING,KVO) notification is not triggered. Whether this will cause problems and depends on the specific object behavior.
Access through properties helps to troubleshoot related errors, because you can add a breakpoint to the Get method and/or set method to monitor the caller of the property and the actual access to it.
There is a reasonable compromise, that is, when the instance variable is written, it is done by "set method", while the instance variable is read directly. This method can not only increase the speed of the read operation, but also control the write operation to the property. The primary reason for writing instance variables through the set method is to ensure that the memory management definition of the relevant properties is implemented.
However, there are several issues to be aware of when choosing this approach.
A question to be aware of is how the property value should be set in the initialization method. In this case, the instance variable should always be accessed directly because the subclass might "overwrite" the setting method. However, in some cases, you must call the Set method in the initialization method: If the instance variable being initialized is declared in the superclass, and we cannot access the instance variable directly in the subclass, then the "set method" needs to be called for a long time.
Another problem to be aware of is "lazy initialization." In this case, the property must be accessed through the Get method, otherwise the instance variable will never be initialized.
When reading data inside an object, it should be read directly through the instance variable, while writing the data should be written by property.
In the initialization method and the Dealloc method, the data should always be read and written directly through the instance variable.
Sometimes a piece of data is configured using lazy initialization techniques, in which case the data needs to be read through the property.
8. Understanding the concept of "object equivalence"
If you want to detect the equivalence of objects, provide "isequal:" with the hash method.
The same object must have the same hash code, but the same object is not necessarily the same as the two hash codes.
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 chance of collisions.
9. Hide implementation Details in "Class family mode"
Subclasses should inherit the abstract base class from the class family.
Subclasses should define their own way of storing data.
Subclasses should overwrite the methods specified in the superclass document that require overwrite.
The class family pattern hides the implementation details behind a set of simple public interfaces.
Class families are often used in system frameworks.
Be careful when inheriting subclasses from the common abstract base class of a class family, if you have a development document, you should read it first.
10. Use associated objects to store custom data in existing classes
The following methods can be used to manage associated objects:
void Objc_setassociatedobject (ID object, void * key, id value, Objc_associationpolicy policy);
This method sets the associated object value for an object with the given key and policy.
When storing object values, you can specify a "storage Policy" to maintain the relevant "memory management semantics." The storage policy is defined by an enumeration named Obj_associationpolicy:
Objc_association_assign Correspondence ASSIGN
Objc_association_retain_nonatomic Correspondence Nonatomic,retain
Objc_association_copy_nonatomic Correspondence Nonatomic,copy
Bojc_association_retain Correspondence RETAIN
Bojc_association_copy corresponding to COPY
ID objc_getassociatedobject (ID object, void * key);
This method obtains the corresponding associated object value from an object based on the given key.
void Objc_removeassociatedobjects (ID object);
This method removes all associated objects from the specified object.
You can connect two objects through the association object mechanism.
When defining an association object, you can specify memory management semantics to mimic the "owning relationship" and "non-owning relationship" used when defining attributes.
Associate objects should be selected only when other practices are not available, because this practice often introduces bugs that are difficult to find.
11, understand the role of Objc_msgsend
In Object-c, if a message is passed to an object, a dynamic binding mechanism is used to determine which method to invoke. At the bottom, all methods are normal C-language functions, however, after the object receives the message, which method is exactly the runtime decision, and even the program runtime changes, these features make objective-c a real dynamic language.
Sending a message to an object can be written like this:
ID returnvalue = [someobject messagename:parameter];
In this case, Someobject is called the "recipient" and MessageName is called the "selector." Select sub-parameters together called "Messages". After the compiler sees this message, it converts it to a standard C-language function call, and the function that is called is the core function in the message-passing mechanism:
void Objc_msgsend (id self, SEL cmd, ...)
The compiler will convert the message from that example to the following function:
ID returnvalue = Objc_msgsend (Someobject,
@selector (messagename:),
parameter);
The Objc_msgsend function invokes the appropriate method based on the type of the recipient and the selector. The method needs to search its "method list" in the class to which the recipient belongs, and if it can find a method that matches the selection sub-name, jump to its implementation code. If not, then follow the inheritance system up and find the right method to jump. If the matching method is not finally found, then the message forwarding operation is performed.
Objc_msgsend will cache the matching results in the "Fast mapping Table", each class has such a cache, if you later also send the same class with the selection of the message, then the execution is very fast, of course, this "fast execution path" is not as fast as "static binding function call operation."
12. Understanding the message forwarding mechanism
When an object receives a message that cannot be read, it initiates a "message forwarding" mechanism that allows the programmer to tell the object how to handle an unknown message by this procedure.
Message forwarding is divided into two major phases. The first stage is to ask the recipient, the class, to see if it can dynamically add methods to handle the current "unknown selector", which is called "dynamic method resolution." The second phase involves a "complete message forwarding mechanism". If the run-time system has completed the first phase, then the recipient can no longer use the dynamic new method to include the message of the selector.
Dynamic Method Parsing
When an object receives a message that cannot be read, the following class methods of the class to which it belongs are called first:
+ (BOOL) Resolveinstancemethod: (SEL) sel;
+ (BOOL) Sesolveclassmethod: (SEL) sel;
The parameter of the method is the unknown selector, and its return value is Boolean, indicating whether the class can add an instance method to handle this selector. This class has the opportunity to add a new method to handle this selector before proceeding to the forwarding mechanism.
The premise of using this approach is that the implementation code for the relevant method has been written, and only waits for the runtime to plug in the class dynamically.
Here are the functions for adding methods:
Class_addmethod (Class cls, SEL name, IMP imp,const char *types);
Class Cos: We need a class, like my [person class].
SEL Name: This is very interesting, this name can be thought of itself, is to add the method in this class is called the name, but the format of the method must be the same as you need to add the format of the method, for example, there are no parameters.
IMP IMP: Add a pointer to a method, IMP is the abbreviation of implementation, it is a pointer to a method implementation, each method has a corresponding Imp. The IMP is needed here, so you can't write the method directly, you need to use a method:
Class_getmethodimplementation (Class cls, SEL name);
const char *types: This thing is actually very well understood:
For example: "[email protected]:" Means this is a void type method, no parameters passed in.
Another example is "[email protected]:" This is an int type method, no parameters are passed in.
Again, such as "[email protected]:@" means that this is an int type method, and another parameter passed in.
Recipients of redundancy
The current recipient has a second chance to handle the unknown selector, and in this step, the runtime system will ask him if he can forward the message to other recipients for processing. The process that corresponds to this step is as follows:
-(ID) Forwardingtargetforselector: (SEL) selector;
The method parameter represents the unknown selector, and if the current recipient can find the redundancy object, return it, and nil if it cannot be found. With this scheme, we can use "combination" to simulate some characteristics of "multiple inheritance". Within an object, there may be a series of other objects that can be returned by this method to the related internal object that will be able to handle a selection, so that it seems to the outside world that the object has handled the messages in person;
Please note that we are unable to manipulate the messages forwarded through this step.
Full message forwarding
The Nsinvocation object is created first, and all the details related to the message that has not been processed are sealed in.
This step calls the following methods to forward the message:
-(Nsmethodsignature *) Methodsignatureforselector: (SEL) aselector{
NSString * selectorstring = Nsstringfromselector (aselector);
if ([selectorstring isequaltostring:@ "Playmusic"]) {
return [nsmethodsignature signaturewithobjctypes: "[email protected]"];
}
return nil;
}
-(void) Forwardinvocation: (nsinvocation *) aninvocation{
NSLog (@ "%@", aninvocation);
[Aninvocation Invokewithtarget:_obj];
}
This method can be implemented simply by changing the invocation target so that the message is invoked on the new target. However, the method implemented in this way is equivalent to the method implemented by the "Redundancy receiver" scheme. The more useful way to do this is to change the message content in some way before triggering the message, such as appending another parameter, or changing the selector.
The recipient has the opportunity to process the message at each step. The more you step back, the greater the cost of processing the message.
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 then use a method to add it to the class.
objects can transfer certain selectors that they cannot interpret to other objects for processing.
After the above two, if there is no way to handle the selection, then start the complete message forwarding mechanism.
13, "Method Deployment Technology" debugging "black Box Method"
Using this feature can be a huge advantage because we do not need the source code or the ability to override the class itself by inheriting subclasses. As a result, the new functionality will take effect in all instances of this class, not just those subclass instances that overwrite the associated method. This scenario is often referred to as "method leveling."
To Exchange method implementations, the following functions are available:
void Method_exchangeimplementations (Method m1, method m2)
The two parameters of this function represent the two method implementations to be exchanged, and the method implementation is obtained by the following functions:
Method Class_getinstancemethod (class AClass, SEL aselector)
This function removes the associated method from the class based on the given selection.
In this scenario, developers can add functionality to black-box methods that "do not know their implementation at all," but few people use the "Method-leveling technology" described above to permanently change the functionality of a class in the context of debugging programs. You must use it only because you have this feature in your objective-c voice. If misused, it makes the code difficult to read and maintainable.
At run time, you can add or replace a method implementation of a selector to a class.
Using another implementation to replace the original method implementation, this process is called "method leveling", developers often use this technology to add new functionality to the original implementation.
Generally speaking, only when debugging the program needs to be implemented in the run-time modification method, this practice should not be abused.
14. Understanding the purpose of "class object"
Each Objective-c object instance is a pointer to a block of memory data. So when declaring a variable, the type is followed by a "*" Character:
NSString *pointervariable = @ "Some string";
For a generic object type ID, because it is already a pointer, we can write this:
ID generictypedstring = @ "Some string";
This is defined in the same way as the definition of NSString *. The only difference is that if a specific type is specified at the time of declaration, the compiler will detect this condition and issue a warning message when a method that it does not have is called on that class instance.
The data structure used to describe the Objective-c object is defined in the header file of the run-time library.
typedef struct OBJC_CLASS *class;
struct Objc_class {
Class Isa;
Class Super_class;
const char *name;
Long version;
Long info;
Long instance_size;
struct Objc_ivar_list *ivars;
struct Objc_method_list **methodlists;
struct Objc_cache *cache;
struct Objc_protocol_list *protocols;
};
This struct stores the "metadata" of a class, such as an instance of a class that implements several methods, with information such as how many instance variables. The first variable of this struct is a variable of the class class that defines the class to which the object belongs, often referred to as the "ISA" pointer. There is also a variable in the struct called Super_class, which defines the superclass of this class.
The Super_class pointer establishes an inheritance relationship, and the ISA pointer describes the class to which the instance belongs. We can find out whether an object can have a corresponding selection, comply with an agreement, and see which part of the inheritance system this object is in.
Querying type information in a class inheritance system
You can use the type information query method to view the class inheritance system. "Ismemberofclass:" is able to determine whether an object is an instance of a particular class, while "Iskindofclass:" can determine whether an object is an instance of a class or its derived class.
You can also use the comparison class object is equal, if so, it is necessary to use the = = operator instead of using the "IsEqual:" Method of comparing Objective-c objects. The reason for this is that the class object is "Singleton", with only one instance of class. In other words, another way to accurately interpret whether an object is an instance of a class is to: [object class] = = [Eocsomeclassclass].
Each instance has a pointer to a class object to indicate its type, and these class objects form the inheritance system of the class.
If the object type cannot be determined by the compiler, then the type information query method should be used to detect it long.
Try to use Type information query methods to determine object types, rather than directly comparing class objects, because some objects may implement message forwarding.
<<effective OBJECTIVE-C 2.0 52 Effective ways to write high-quality iOS and OS X code >> notes-objects, messages, run-time