新的属性关键字
- nullable
可能为空,属性修饰符
nullable 语法1
@property (nonatomic, strong, nullable) NSString *name;
nullable 语法2 * 关键字 变量名
@property (nonatomic, strong) NSString * _Nullable name;
nullable 语法3
@property (nonatomic, strong) NSString * __nullable name;
- nonnull
不能为空,属性修饰符
nonnull 语法1
@property (nonatomic, strong, nullable) NSString *name;
nonnull 语法2 * 关键字 变量名
@property (nonatomic, strong) NSString * _Nonnull name;
nonnull 语法3
@property (nonatomic, strong) NSString * __nonnull name;
- null_resettable
必须要处理为空情况,重写get方法,get方法不能返回nil,set可以传入为空
@property (nonatomic, strong, null_resettable) NSString *name;
-
_Null_unspecified
不确定是否为空 -
宏定义
NS_ASSUME_NONNULL_BEGIN & NS_ASSUME_NONNULL_END
修饰的范围,默认是nonnull
NS_ASSUME_NONNULL_BEGIN
@interface ViewController : UIViewController
@property (nonatomic, assign) int name;
@end
NS_ASSUME_NONNULL_END
新的泛型
为什么要推出泛型?迎合swift
泛型作用:1.限制类型 2.提高代码规划,减少沟通成本,一看就知道集合中是什么东西
泛型定义用法:类型<限制类型>
泛型声明:在声明类的时候,在类的后面<泛型名称>
泛型仅仅是报警告
泛型好处:1.从数组中取出来,可以使用点语法
2.给数组添加元素,有提示
泛型在开发中使用场景:1.用于限制集合类型
id是不能使用点语法
为什么集合可以使用泛型?使用泛型,必须要先声明泛型? => 如何声明泛型
自定义泛型?
什么时候使用泛型?在声明类的时候,不确定某些属性或者方法类型,在使用这个类的时候才确定,就可以采用泛型
自定义Person,会一些编程语言(iOS,Java),在声明Person,不确定这个人会什么,在使用Person才知道这个Person会什么语言
如果没有定义泛型.默认就是id
使用示范:
声明Person类
@interface Person<ObjectType> : NSObject
// 属性
@property (nonatomic, strong) ObjectType language;
@end
声明Language类
#import <Foundation/Foundation.h>
@interface Language : NSObject
@end
声明iOS类,其父类为Language
#import "Language.h"
@interface iOS : Language
@end
泛型的使用
#import "Person.h"
#import "Java.h"
#import "iOS.h"
@interface ViewController ()
@property (nonatomic, strong) NSMutableArray<NSString *> *arr;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Java *java = [[Java alloc] init];
iOS *ios = [[iOS alloc] init];
// iOS
Person<iOS *> *p = [[Person alloc] init];
p.language = ios;
// Java
Person<Java *> *p1 = [[Person alloc] init];
p1.language = java;
}
协变和逆变
__covariant:协变, 表示子类可转父类
__contravariant:逆变,表示父类可转子类
@interface Person<__contravariant ObjectType> : NSObject
// 语言
@property (nonatomic, strong) ObjectType language;
@end
__kindof
表示当前类或者它的子类
@interface Person : NSObject
// xcode5 才出 instancetype
// Xcode5之前使用 id
// instancetype:自动识别当前类的对象
//__kindof表示返回值是Person类或其子类
+ (__kindof Person *)person;
@end
网友评论