Objective-c New Syntax Features

Source: Internet
Author: User



2007, Objective-c in the Tiobe programming language ranked in the poor 45th place, and with the rapid development of mobile internet and iphone,ipad, such as the broad market prospects of iOS devices, objective-c also quickly rise, into the developer's vision. In the recent Tiobe rankings, Objective-c reached an astonishing 4th place, which can be said to have become a very important programming language in the world today.



And the objective-c is now largely maintained by Apple in charge. In order to adapt to development needs, Apple has been perfecting OC and the corresponding cocoa library, the property introduced in 2.0, with the block introduced by IOS4, and the arc introduced last year, have been welcomed by most developers. Almost every year there are significant characteristics of the accession, which is not available in every language, but also these features have brought a lot of convenience for everyone.



This year WWDC is no exception, and OC and LLVM will be significantly improved. This article will be a simple collation and review of these improvements.


Method Order


If you have the following code:




@interface SongPlayer : NSObject 
- (void)playSong:(Song *)song; 
@end 

@implementation SongPlayer 
- (void)playSong:(Song *)song { 
    NSError *error; 
    [self startAudio:&error]; 
    ... 
} 

- (void)startAudio:(NSError **)error { ... } 
@end




In the earlier compilation environment, the above code would appear at [self startaudio:&error] with a warning that the instance method did not find. Because of the compilation order, the compiler is not aware that after the-playsong: method There is a-startaudio:, so give a warning. There are two previous solutions: either move the implementation of-startaudio: to the top of-playsong:, or declare-startaudio in the Category: (by the way.) Take-startaudio: It is completely wrong to get the. h file directly, as this method should not be public. The former destroys the structure of the. m file, which disrupts the order of the methods, resulting in later maintenance trouble; the latter writes extra unnecessary code to make the. m file longer. Neither of these methods is a good solution either.



Now there's no need to have a headache again, LLVM has added a new feature, and now directly use the code above, no additional processing is required to avoid the warning. The new compiler changed the behavior of the previous sequential compilation by first scanning the method declaration and then compiling the method implementation. Thus, in the same implementation file, regardless of where the method is written, the compiler can know the names of all the methods before compiling the method implementation, thus avoiding the warning.


Enumeration improvements


Starting with Xcode4.4, there's a better notation for enumerations:




typedef enum NSNumberFormatterStyle : NSUInteger {
    NSNumberFormatterNoStyle, 
    NSNumberFormatterDecimalStyle, 
    NSNumberFormatterCurrencyStyle, 
    NSNumberFormatterPercentStyle, 
    NSNumberFormatterScientificStyle, 
    NSNumberFormatterSpellOutStyle 
} NSNumberFormatterStyle;




The enumeration type is Nsuinteger when the enumeration list is listed, and the benefit of the previous direct enumeration and the first enumeration of the type of rebinding is convenient for the compiler to give a more accurate warning. Personally, it is not particularly useful for the general developer, as it often does not involve very complex enumerations and is not confused with the previous enumeration declaration methods. So it is better to use the same enumeration method. But it's better to try this new method if you have a condition or have not formed your own habits or to start a new project, because it is relatively strict.


Property Auto-binding


There is no doubt that everyone loves to use property. But when writing the property, it is generally necessary to correspond to write instance variables and corresponding synthesis, this is really a thing that makes people happy not to get up. Apple has done some work before, at least removing the requirement to write instance variables. The value after the equal sign in synthesis is the strength variable name. now Apple goes a step further and brings us very good news: Don't write synthesis anymore! after Xcode 4.4, synthesis now automatically generates the corresponding property.



By default, for the property foo, the compiler automatically complements the synthesis for the developer in the implementation file, as if you wrote @synthesis foo = _foo; The default instance variable begins with an underscore, followed by the property name. If you have written synthesis, will be written by the developer himself synthesis, such as write only @synthesis foo, then the instance variable name is foo. If there is no synthesis and you implement-foo and-setfoo: Then the property will not correspond to the instance variable. And if only one of the getter or setter is implemented, the other method will automatically help generate (even if there is no write synthesis, of course ReadOnly's property says otherwise).



To write the implementation of the @dynamic, all the corresponding synthesis will not take effect (even if there is no write synthesis, this is the inevitable runtime), it can be understood to write the dynamic words setter and getter must be determined by the runtime.



To summarize, the new property binding rules are as follows:


    • Unless the developer provides a getter or setter in the implementation file, it is automatically generated
    • Instance variables are generated automatically unless the developer provides getter and setter at the same time
    • As long as the synthesis is written, the instance variable is generated regardless of the instance variable name.
    • Dynamic priority higher than synthesis
Shorthand


OC syntax has always been considered cumbersome, and the vast majority of messages are sent with a long function name. In fact, this is a double-edged sword, the good aspect, it makes the code quite easy to read, because almost all of the methods are described in full English, and if you follow the naming rules, parameter types and methods of action is clear, but the bad aspect, it makes coding time to more than a lot of unnecessary keyboard percussion , reducing the development efficiency. Apple realizes this by introducing a series of column rules to simplify OC in the new LLVM. After simplification, in order to reduce the readability of the cost, in exchange for a slightly faster development time, can be said to be more in line with the current short development cycle needs. The simplified OC code looks a step closer to a fast-developing language like Perl or Python, and as a practical matter, it's yen che different ... At least I'm not particularly fond of certain abbreviations. Probably because see shorthand code has not formed intuition, always have to reflect a moment to know what this is ...


NSNumber


All the [NSNumber numberwith ...:] methods can be abbreviated:


    • [NSNumber numberWithChar:‘X’]abbreviated to@‘X’;
    • [NSNumber numberWithInt:12345]Shorthand for@12345
    • [NSNumber numberWithUnsignedLong:12345ul]Shorthand for@12345ul
    • [NSNumber numberWithLongLong:12345ll]Shorthand for@12345ll
    • [NSNumber numberWithFloat:123.45f]Shorthand for@123.45f
    • [NSNumber numberWithDouble:123.45]Shorthand for@123.45
    • [NSNumber numberWithBool:YES]Shorthand for@YES


Well... A lot of convenient AH ~ before the most annoying is the number put in the array is also encapsulated into NSNumber ... Now the words directly with @ at the beginning of the number, can simplify a lot.


Nsarray


Some of the Nsarray methods are simplified:


    • [NSArray array]Shorthand for@[]
    • [NSArray arrayWithObject:a]Shorthand for@[ a ]
    • [NSArray arrayWithObjects:a, b, c, nil]Shorthand for@[ a, b, c ]


It can be understood that the @ symbol represents the NS object (as with NSString's @), followed by a square bracket [] that is common in many other languages to represent the array. In fact, when we use shorthand, the compiler automatically translates it into our common code. For example, for @[A, B, c], the actual compile-time code is




// compiler generates: 

id objects[] = { a, b, c }; 
NSUInteger count = sizeof(objects)/ sizeof(id); 
array = [NSArray arrayWithObjects:objects count:count];




It is important to note that if there is nil in A,b,c, an exception will be thrown when generating nsarray, rather than forming an incomplete nsarray like [Nsarray arraywithobjects:a, B, C, nil]. In fact, this is a good feature to avoid the existence of difficult to find bugs.


Nsdictionary


Since the array has been simplified, the dictionary has not run, or Perl, Python, Ruby, is very similar to the expected wording:


    • [NSDictionary dictionary]Shorthand for@{}
    • [NSDictionary dictionaryWithObject:o1 forKey:k1]Shorthand for@{ k1 : o1 }
    • [NSDictionary dictionaryWithObjectsAndKeys:o1, k1, o2, k2, o3, k3, nil]Shorthand for@{ k1 : o1, k2 : o2, k3 : o3 }


and arrays like, when writing down @{k1:o1, K2:o2, K3:o3}, the actual code will be




// compiler generates: 
id objects[] = { o1, o2, o3 }; 
id keys[] = { k1, k2, k3 }; 
NSUInteger count = sizeof(objects) / sizeof(id); 
dict = [NSDictionary dictionaryWithObjects:objects forKeys:keys count:count];



mutable version and static version


The version generated above is immutable, and if you want a variable version, you can send a-mutablecopy message to generate a mutable copy. Like what




NSMutableArray *mutablePlanets = [@[ 
                                  @\\"Mercury\\", @\\"Venus\\", 
                                  @\\"Earth\\", @\\"Mars\\", 
                                  @\\"Jupiter\\", @\\"Saturn\\", 
                                  @\\"Uranus\\", @\\"Neptune\\" ] 
                                  mutableCopy];




In addition, for arrays marked as static (there is no static dictionary: Hashing and sorting are done at compile time and the key of the cocoa framework is not a constant, and you cannot use shorthand to assign a value (in fact, the original traditional notation is not). The workaround is to assign a value to static in the class method + (void) Initialize, for example:




static NSArray *thePlanets; 
+ (void)initialize { 
    if (self == [MyClass class]) { 
        thePlanets = @[ @\\"Mercury\\", @\\"Venus\\", @\\"Earth\\", @\\"Mars\\", @\\"Jupiter\\", @\\"Saturn\\", @\\"Uranus\\", @\\"Neptune\\" ]; 
    } 
}



Subscript


In fact, one of the main purposes of using these abbreviations is to use subscripts to access elements:


    • [_array objectAtIndex:idx]abbreviated to_array[idx];
    • [_array replaceObjectAtIndex:idx withObject:newObj]Shorthand for_array[idx] = newObj
    • [_dic objectForKey:key]Shorthand for_dic[key]
    • [_dic setObject:object forKey:key]Shorthand for_dic[key] = newObject


is convenient, but it is important to note that the dictionary is also square brackets [], rather than the imagined curly braces {}. It is estimated that you want to avoid conflicts with the curly braces of the code block ... The actual working principle of shorthand is actually simply the shorthand of the corresponding method, no surprises.



But there was a surprise. That is to use a similar set of methods, you can do for our own classes, you can also use subscript to access. And to achieve this, we need to implement the following methods,



For arrays of similar structure:




- (elementType)objectAtIndexedSubscript:(indexType)idx; 

- (void)setObject:(elementType)object atIndexedSubscript:(indexType)idx;




For a dictionary-like structure:




- (elementType)objectForKeyedSubscript:(keyType)key; 

- (void)setObject:(elementType)object forKeyedSubscript:(keyType)key;



Fixed bridging


For arc, the most confusing and error-prone area is probably the concept of bridging. Because of historical reasons, the conversion of CF objects and NSObject objects has always had some subtle relationships, and after the introduction of arc, these relationships become complex: it is primarily to be clear whether the issue of memory management should be either CF or NSObject (for arc and more detailed instructions, You can see an ARC starter Tutorial I wrote earlier.



After Xcode4.4, it is possible to blur the work before distinguishing who owns the object. In the code block interval plus CFimplicitbridgingenabled and CFimplicitbridgingDISABLED, In the previous bridging transformation, you can simply write a cast between the CF and NS without the need to add the __bridging keyword. Who's going to take care of this memory? Give the system a headache.


Objective-c is indeed a rapidly changing language. On the one hand, its dynamic characteristics and small talk brand deeply not go, on the other hand, it is actively moving towards the grammatical direction of a variety of simple languages. Various types of automated processing are not reassuring, but it turns out that they are working well and that they do save time for developers. Try to embrace the new changes as soon as possible ~


Objective-c New Syntax Features


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.