ios9新特性(关键字)

嗯嗯,马上就要 发布iOS新的版本了。嗯,码农又该忙碌了

ios9新特性(关键字)

新出的关键字:修饰属性,方法的参数,方法返回值,规范开发。

好处

1.提高程序员规范,减少交流成本,

1.nonnull 不可为空

nonnull:表示属性不能为空,non:非,null:空
方式一:
@property (nonatomic, strong, nonnull) NSString *name;
方式二:
@property (nonatomic, strong) NSString * _Nonnull name;
方式三:
@property (nonatomic, strong) NSString * __nonnull name;

2.nullable 可为空

nullable:可以为nil
方式一:
@property (nonatomic, strong, nullable) NSString *name;
方式二:
@property (nonatomic, strong) NSString * _Nullable name;
方式三:
@property (nonatomic, strong) NSString * __nullable name; 

3.null_resettable:可以重新设置空,set方法可以为空,get不能为空。

 方式一:
 @property (nonatomic, strong, null_resettable) NSString *name;
 注意:用null_resettable属性,必须重写set,或者get方法,处理传值为nil的情况,可以模仿控制器view的get方法,当view为nil,就自己创建一个.

4._Null_unspecified:不确定是否为空.

方式一:
@property (nonatomic, strong) NSString * _Null_unspecified name;

5.泛型:限制类型

泛型书写格式:放在类型后面,表示限制这个类型.

定义一个类

@interface Person : NSObject

@property (nonatomic, strong) ObjectType name;

@end 

然后使用的时候

Person *p = [[Person alloc] init];
p.name = 这里就会提示赋值 NSString* 这个类型

6.协变,逆变

  • 泛型中协变,逆变,用于转换类型
  • 默认带有泛型的变量,互相赋值有报警告,使用协变,逆变,就能解决.
  • 协变(__covariant): 向上转型, 子类转父类。
  • 逆变(__contravariant):向下转型 父类转子类(因为子类的属性,父类不一定有)
// IOS : Language (IOS 继承自 Language)
Person *person = [[Person alloc] init];
Person *person1 = [[Person alloc] init];

// (协变)
Person = Person1;

//(逆变)
person1 = person;

7.__kindof

__kindof:相当于,表示某个类或者他的子类。

设计模型中可以使用,当给某个类提供类方法,想让外界调用能看到创建什么对象,并且不报警告。

@interface Person : NSObject

// 会自动识别当前对象的类
// SonPerson (SonPerson : Person)
//+ (instancetype)person;

// 在外面使用的时候,例如
[SonPerson person]
//+ (instancetype)person; 就会变成
//+ (SonPerson *)person; 


// __kindof Person *:表示可以是Person类或者它的子类
+ (__kindof Person *)person;

// 仅仅表示只能是Person类
+ (Person *)person1;

@end

你可能感兴趣的:(ios9新特性(关键字))