歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> iOS6下Objective-C最新特性

iOS6下Objective-C最新特性

日期:2017/3/1 10:00:19   编辑:Linux編程

WWDC2012發布了iOS6,同時為Objective C帶來了一些新特性以簡化編程。下面是這些新特性,需要XCode4.4及以上版本支持:

1.方法的申明順序不再要求
在方法裡面可以調用在後面申明的方法,編譯器會幫助查找方法的申明,順序不再要求。如下:

@interface SongPlayer : NSObject
- (void)playSong:(Song *)song;
@end
@implementation SongPlayer
- (void)playSong:(Song *)song {
NSError *error;
[self startAudio:&error];//XCode4.4以前會提示方法未定義,XCode4.4以後可以放心使用
...
}
- (void)startAudio:(NSError **)error { ... }
@end

2.枚舉支持強類型
XCode4.4以前定義枚舉使用如下方式,相當於定義了類型為int的枚舉類型。

typedef enum {
NSNumberFormatterNoStyle,
NSNumberFormatterDecimalStyle,
NSNumberFormatterCurrencyStyle,
NSNumberFormatterPercentStyle,
NSNumberFormatterScientificStyle,
NSNumberFormatterSpellOutStyle
} NSNumberFormatterStyle;
// typedef int NSNumberFormatterStyle;

XCode4.4以後可以為枚舉指明強類型,這樣在賦值時會有強類型限制(需要在Build Setting開啟Suspicious implicit conversions)。定義如下:

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

或使用NS_ENUM宏來定義

typedef NS_ENUM(NSUInteger, NSNumberFormatterStyle) {
NSNumberFormatterNoStyle,
NSNumberFormatterDecimalStyle,
NSNumberFormatterCurrencyStyle,
NSNumberFormatterPercentStyle,
NSNumberFormatterScientificStyle,
NSNumberFormatterSpellOutStyle
};

3.默認屬性合成

@interface Person : NSObject
@property(strong) NSString *name;
@end
@implementation Person {
NSString *_name;//這句可以省略,XCode很早就可以了
}
@synthesize name = _name;//XCode4.4以後,這句也可以省略,XCode默認合成帶下劃線的成員變量
@end

即可以簡化為:

@interface Person : NSObject
@property(strong) NSString *name;//ARC開啟,否則需要自己release
@end
@implementation Person
@end

Copyright © Linux教程網 All Rights Reserved