通过NSURLSessionConfiguration对类属性property(class)的思考

14 篇文章 0 订阅

在查看NSURLSessionConfiguration的头文件时看到了如下的定义

#if FOUNDATION_SWIFT_SDK_EPOCH_AT_LEAST(8)
@property (class, readonly, strong) NSURLSessionConfiguration *defaultSessionConfiguration;
@property (class, readonly, strong) NSURLSessionConfiguration *ephemeralSessionConfiguration;
#endif

@property (class)的写法使我不禁想起了前一阵看的一篇文章 点击打开链接,了解到了ios新增了对类属性的支持,里面还举了实例,演示如何去定义实现类属性

文中提到了由于类属性是类级别的而不是实例变量,所以把它们声明为静态的,后面它的实例代码也都是以类属性应为静态的前提下编写的,今天看到了NSURLSessionConfiguration也有两个类属性defaultSessionConfiguration、ephemeralSessionConfiguration,于是决定验证一下文章的说法,结果发现

NSURLSessionConfiguration *config1 = [NSURLSessionConfiguration defaultSessionConfiguration];
 
NSURLSessionConfiguration *config2 = [NSURLSessionConfiguration defaultSessionConfiguration];

config1与config2的地址并不一致, defaultSessionConfiguration应该并不是静态变量

 * The shared session uses the global singleton credential, cache
 * and cookie storage objects.
 *
 * An ephemeral session has no persistent disk storage for cookies,
 * cache or credentials.
继续实验,发现

NSLog(@"%@",config1.URLCache);
NSLog(@"%@",config2.URLCache);
NSLog(@"%@",config1.URLCredentialStorage);
NSLog(@"%@",config2.URLCredentialStorage);


它们的URLCache、URLCredentialStorage对象都是一样的

所以我觉得它们的内部实现应该是类似这样的:

#import <Foundation/Foundation.h>

@interface MyURLSessionConfiguration : NSObject

@property (class,readonly,strong) MyURLSessionConfiguration *defaultSessionConfiguration;
@property (strong) NSURLCache *URLCache;

@end
#import "MyURLSessionConfiguration.h"

@implementation MyURLSessionConfiguration

+(MyURLSessionConfiguration *)defaultSessionConfiguration
{
    //MyURLSessionConfiguration每次都分配新的
    MyURLSessionConfiguration *configuration = [[MyURLSessionConfiguration alloc] init];
    //但URLCache都统一分配统一对象(NSURLCache单例)
    configuration.URLCache = [NSURLCache sharedURLCache];
    return configuration;
}

@end
MyURLSessionConfiguration *config1 = [MyURLSessionConfiguration defaultSessionConfiguration];
MyURLSessionConfiguration *config2 = [MyURLSessionConfiguration defaultSessionConfiguration];
NSLog(@"%@,%@",config1,config1.URLCache);
NSLog(@"%@,%@",config2,config2.URLCache);


思考总结:

类属性的出现,从语法层面上对类一层级上属性的定义提供了支持,是从类级别上一种对属性定义和控制的方式,但具体如何去控制和使用,看实际需求是十分灵活的。没有规定说类属性就一定要是所有类实例对应同一个属性对象,与static更没有必然的联系。

如上面的例子中,通过类属性,虽然每次生成的SessionConfiguration都不一样,但却很好的控制了所有生成的SessionConfiguration对象都绑定了同一个cache实例。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值