Effective OBJECTIVE-C 2.0 Learning record

Source: Internet
Author: User

As a result of the recent entry, the company arranged to study freely, so there is time to effective OBJECTIVE-C 2.0 a book to study again. As a result of the narrow personal knowledge, some of the contents of the book can not be understood thoroughly, now will be learned to do the understanding of the content to do a comb, the personal think of common and important knowledge recorded, for future reference.

  1. Introduce as few other header files as possible in the header file of the class

The timing of the introduction of the header file is delayed as much as possible, and is introduced (such as. m files) when there is a need. Because other header files are introduced into the header file, the compilation time is increased (it may be better to run the hardware now, so there is no sense in this point). To use a different class in the header file, use "forward declaration"-@class + class name.

  2. Multi-use type constants, less # define preprocessing directives

Because constants defined with pre-processing directives do not contain type information, the compiler will only look for replacements, and the compiler will not generate a warning even if a constant value has been redefined. The recommended way to use this is

// the # define #define Animation_duration 0.3// the staticconst0.3is represented by a sentence code ;

This allows you to not only know the constant type but also restrict the data to use in this type of file

  3. Using enumerations to represent States, options, status codes

The novice writer may write the enumeration directly and write its state

enum pspconnectionstate{    1,    pspconnectionstateconnecting,    Pspconnectionstateconnected,}pspconnectionstate;

At first glance there seems to be nothing wrong with the line, but if you change the way you write the enumeration, it is written as follows

//Radio State Enumerationtypedef ns_enum (Nsuinteger, pspconnectionstate) {pspconnectionstatedisconnected=1, Pspconnectionstateconnecting, pspconnectionstateconnected,};//Check State enumerationtypedef ns_options (Nsuinteger, pspconnectionstate) {pspconnectionstatedisconnected=1<<0, Pspconnectionstateconnecting=1<<1, pspconnectionstateconnected=1<<2,};

This defines the enumeration type with the Ns_enum and Ns_options macros, and indicates the underlying data type of the device, in addition to ensuring that the enumeration is implemented by the developer's chosen underlying data type, and can be easily viewed and used by other developers. also note that when working with Enum types, you can use the switch statement as much as possible, and do not implement the default branch, so that after the new enumeration is added, the compiler will remind the developer that the switch statement does not handle all enumerations.

  4. Try to access instance variables directly inside the object

Direct access to instance variables is faster because it does not pass the Objective-c "method Dispatch" step, but because direct access to the instance variable does not trigger "key-value Observations" (KVO), it is recommended to read the data directly through the instance variable, while writing the data by using the property to write ( Point syntax). Of course, for lazy-loaded properties, you need to read the data through properties.

  5. Understanding the message forwarding mechanism

Message forwarding is divided into two phases: the first stage is to ask the recipient class to see if it can dynamically add methods to handle the current "unknown selector", which is called "dynamic method parsing". The second phase involves a "complete message forwarding mechanism". The whole message forwarding process is passed to represent

Here the simulation is added in the dynamic method parsing method below for the code example

=======.h file in =========@interfaceBqautodictionary:nsobject//arbitrarily created properties@property (nonatomic, copy) NSString *string; @property (nonatomic, strong) NSNumber*Number ; @property (nonatomic, strong) NSDate*date; @property (nonatomic, Strong)IDOpaqueobject;@end=======.M file in =========@interfacebqautodictionary () @property (nonatomic, strong) Nsmutabledictionary*Backingstore;@end@implementationBqautodictionary
///Do not dynamically generate the Get,set method @dynamicstring, number, date, opaqueobject;-(instancetype) init{ Self=[Super Init]; if(self) {_backingstore= [NsmutabledictionaryNew]; } returnSelf ;}+(BOOL) Resolveinstancemethod: (SEL) sel{//get Unable to process message nameNSString *selectorstring =nsstringfromselector (SEL); NSLog (@"%s", __func__); //adding set and get methods dynamically if([selectorstring Hasprefix:@"Set"]) { /** * Dynamic Add Set method * @param self category * @param sel method Selector * @param IMP requires an additional method /c0>*/Class_addmethod (Self, SEL, (IMP) Autodictionarysetter,"[Email protected]:@"); }Else{Class_addmethod (self, SEL, (IMP) Autodictionarygetter,"@@:"); } returnYES; //If you cannot process the message, you need to return to the following method for message forwarding//return [Super Resolveinstancemethod:sel];}IDAutodictionarygetter (IDSelf , SEL _cmd) { //get the dictionary in the instanceBqautodictionary *typedself = (Bqautodictionary *) Self; Nsmutabledictionary*backingstore =Typedself.backingstore; //get names based on selectorsNSString *key =Nsstringfromselector (_cmd); NSLog (@"Getter Name =%@", key); //return value return[Backingstore Objectforkey:key];}voidAutodictionarysetter (IDSelf, SEL _cmd,IDvalue) {Bqautodictionary*typedself = (Bqautodictionary *) Self; Nsmutabledictionary*backingstore =Typedself.backingstore; NSString*selectorstring =Nsstringfromselector (_cmd); Nsmutablestring*key =[selectorstring mutablecopy]; NSLog (@"Setter Name =%@", key); //remove ': ' character[Key Deletecharactersinrange:nsmakerange (Key.length-1,1)]; //remove ' Set ' character[Key Deletecharactersinrange:nsmakerange (0,3)]; //change the initial letter to lowercaseNSString *lowercasefirstchar = [[Key substringtoindex:1] lowercasestring]; [Key Replacecharactersinrange:nsmakerange (0,1) Withstring:lowercasefirstchar]; if(value) {[Backingstore setobject:value forkey:key]; }Else{[Backingstore removeobjectforkey:key]; }}@end

  6. Avoid namespace collisions with prefixes

Because of the frequent naming duplication problem with developer file consolidation, there is no namespace mechanism for objective-c. Therefore, the way to avoid file renaming is to add the appropriate prefix to all the names. Apple Xuancheng retains the right to use all the "two-letter prefixes", so the prefix we choose should be three letters!

  7. Use immutable objects as much as possible

Properties are read-write, so that the classes are mutable. In general, the data we want to model doesn't necessarily need to change. For example, after the data request of the network service, we just display the data on the line. Of course, if an attribute can only be modified inside an object, it can be extended from ReadOnly to ReadWrite in the extension. Examples such as the following

=====.h file ======@interfacereadonly) NSString *name; @end=====.m file ======@interface*name; @end

  8. In the Dealloc method, just put the reference and dismiss the listener

The object will eventually be reclaimed by the system after the lifetime of the experience, and then the Dealloc method will be executed, because the object is already in the recycle state, so no other things should be done within this method. Just release references to other objects inside, and cancel notifications such as "key-value Observations" (KVO) or Nsnotificationcenter, which were originally subscribed! Note that other non-OBJECTIVE-C objects owned by the object need to be released manually here, and if you manage memory manually, you will need to call [Super Dealloc] at the end .

  9. Multi-use dispatch queue, less use of synchronous lock

In previous code writing, the usual practice with thread-safety issues was to add the lock directly. The method of adding a line lock is good, but there are flaws, for example, in extreme cases, the synchronization block back to the deadlock, but also the efficiency is not high enough. Here you need to introduce a simple and efficient way to use the "Serial synchronization queue", using the following

_syncqueue = Dispatch_queue_create ("PSP"0); -(NSString *) name{    *localname;     ^{        = _name;    });     return LocalName;} -(void) SetName: (NSString *) name{    ^{        = name;    });}

Of course there is a more efficient way to use fences (barrier), fence blocks must be executed separately and not parallel to other blocks (only meaningful for concurrent queues)

//Parallel Queues_syncqueue = Dispatch_get_global_queue (Dispatch_queue_priority_default,0);//with synchronous-(NSString *) name{__block nsstring*LocalName; Dispatch_sync (_syncqueue,^{localname=_name;    }); returnLocalName;}//using an asynchronous fence block- (void) SetName: (NSString *) name{Dispatch_barrier_async (_syncqueue,^{_name=name; });}

  10. Use Nscache instead of nsdictionary when building cache

In how the network request is cached, most programmers may be using nsdictionary directly, in fact the Nscache class is better, it is the foundation framework specifically designed to handle this task Nscache more than Nsdicitionary, It can automatically delete the cache when the system resources are going to be exhausted. If you use a common dictionary, then you need to write your own hooks (I don't know what that means). In addition, Nscache will remove the oldest unused object. There is also a class called Nspurgeabledata (Nsmutabledata sub-Class), and Nscache with the use of the effect is very good. Specific use of the method can be self-baidu!

The above is the individual feel the need to tidy up the knowledge, if there is anything wrong, please point out, thank you!

    

Effective objective-c 2.0 Learning record

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.