allocWithZone

本文介绍了allocWithZone方法的作用,即为对象分配足够的内存,并由Cocoa遍历成员变量以确定所需内存大小。此方法已废弃但仍保留以解决历史问题。在实现单例模式时,通常会重写此方法以确保单例的唯一性。
- 是什么
  • 和alloc一样,为该对象分配足够的内存 cocoa 会遍历该对象所有的成员变量,通过成员变量的类型来计算所需占用的内存。

  • 已被废弃,留着只是因为历史问题。

  • 使用alloc方法初始化一个类的实例的时候,默认是调用了 allocWithZone 的方法。

- 怎么用
  • 在单例类里面,覆盖allocWithZone方法的原因:为了保持单例类实例的唯一性,需要覆盖所有会生成新的实例的方法
#import "TPNetResqustManager.h" #import <TPHTTPClient/TPHTTPClient.h> #import <TPHandle-ObjC/TPHandle.h> #import <TPHandle-ObjC/TPGCDReprocessHandle.h> #import <TPHandle-ObjC/TPAbstractHandle.h> #import <TPHTTPClient/TPHTTPResponse.h> #import <TPHTTPClient/TPHTTPResponseConfig.h> #import "TPSecurityPolicy.h" #import "TPNetworkUtil.h" @interface TPNetResqustManager() <NSURLSessionDelegate> @property(nonatomic, strong) dispatch_queue_t seriaQueue; @property(nonatomic, strong) NSMutableDictionary *serverDomain; @end static const NSInteger kTPRequestTimeOut = 30; @implementation TPNetResqustManager - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{ NSURLCredential *card = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust]; completionHandler(NSURLSessionAuthChallengeUseCredential,card); } + (instancetype)shareInstance { static dispatch_once_t onceToken; static TPNetResqustManager *instance = nil; dispatch_once(&onceToken, ^{ if (instance == nil) { instance = [super allocWithZone:nil]; instance.seriaQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL); instance.serverDomain = [NSMutableDictionary new]; } }); return instance; } + (instancetype)allocWithZone:(struct _NSZone *)zone { return [TPNetResqustManager shareInstance]; } #pragma mark - + (void)postWithUrl:(NSString *)url params:(NSDictionary *)params succeedBlk:(TPNetSucceedBlk)sucBlk failureBlk:(TPNetFailureBlk)failureBlk { [self postWithUrl:url header:nil params:params succeedBlk:sucBlk failureBlk:failureBlk]; } + (void)getWithUrl:(NSString *)url params:(NSDictionary *)params succeedBlk:(TPNetSucceedBlk)sucBlk failureBlk:(TPNetFailureBlk)failureBlk { [self getWithUrl:url header:nil params:params succeedBlk:sucBlk failureBlk:failureBlk]; } + (void)postWithUrl:(NSString *)url header:(NSDictionary *)header params:(NSDictionary *)params succeedBlk:(TPNetSucceedBlk)sucBlk failureBlk:(TPNetFailureBlk)failureBlk { [self requstWithUrl:url header:header method:TPHTTPRequestConfigRequestMethodPOST params:params succeedBlk:sucBlk failureBlk:failureBlk]; } + (void)getWithUrl:(NSString *)url header:(NSDictionary *)header params:(NSDictionary *)params succeedBlk:(TPNetSucceedBlk)sucBlk failureBlk:(TPNetFailureBlk)failureBlk { [self requstWithUrl:url header:header method:TPHTTPRequestConfigRequestMethodGET params:params succeedBlk:sucBlk failureBlk:failureBlk]; } + (void)requstWithUrl:(NSString *)url header:(NSDictionary *)header method:(NSString *)method params:(NSDictionary *)params succeedBlk:(TPNetSucceedBlk)sucBlk failureBlk:(TPNetFailureBlk)failureBlk { TPHTTPRequest *request = [TPHTTPRequest new]; request.timeout = kTPRequestTimeOut; request.httpConfig.url = url; request.httpConfig.method = method; [request.httpConfig.header addEntriesFromDictionary:[TPNetworkUtil defaultHeaders]]; header ? [request.httpConfig.header addEntriesFromDictionary:header] : nil; [TPNetResqustManager shareInstance].reqHeaderBlk ? [TPNetResqustManager shareInstance].reqHeaderBlk(request.httpConfig.header) : nil; #if DEBUG NSLog(@"tprequest:%@ \nheader:%@ \nbody:%@\n", url, header, params); #endif request.httpConfig.body = params; NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"tp-link-CA.der"]; // TPHTTPClient *client = [self certClient:path]; TPHTTPClient *client = [self defaultClient]; [TPGCDReprocessHandle reprocessFromHandle:[client sendRequest:request] queue:dispatch_get_main_queue() reprocessAction:^TPHandleResult * _Nullable(TPHandleResult<TPHTTPResponse *> * _Nonnull result) { [client.sessionManager.session finishTasksAndInvalidate]; if (!result.success) { NSDictionary *codeDict = @{ @"httpStatusCode": @(result.obj.httpConfig.statusCode), @"httpErrorCode": @(result.obj.httpConfig.urlErrorDomainCode), }; NSMutableDictionary *dict = [NSMutableDictionary new]; dict[@"statusCode"] = codeDict; if (result.obj.httpConfig.body) { dict[@"content"] = result.obj.httpConfig.body; } NSError *err = [NSError errorWithDomain:@"tplink.com" code:1 userInfo:dict]; failureBlk ? failureBlk(err) : nil; return nil; } sucBlk ? sucBlk(result.obj.httpConfig.body) : nil; return nil; }]; } #pragma mark - Private + (TPHTTPClient *)defaultClient { return [self certClient:@""]; } + (TPHTTPClient *)certClient:(NSString *)certPath { TPHTTPClient *client = [TPHTTPClient new]; NSMutableSet *types = client.sessionManager.responseSerializer.acceptableContentTypes.mutableCopy; [types addObjectsFromArray:@[@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain"]]; client.sessionManager.responseSerializer.acceptableContentTypes = types; NSData *data = [NSData dataWithContentsOfFile:certPath.length > 0 ? certPath : @""]; if (data) { AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:[NSSet setWithObject:data]]; policy.allowInvalidCertificates = YES; policy.validatesDomainName = YES; client.sessionManager.securityPolicy = policy; } else { client.sessionManager.securityPolicy = [TPSecurityPolicy defaultPolicy]; } return client; } @end .m,这就能直接使用了吗?假如我有一个接口url的话
12-16
#import <Foundation/Foundation.h> #import <TPHTTPClient/TPHTTPRequest.h> @class TPSSError; @class TPNetResqustManager; typedef void (^TPNetSucceedBlk)(NSDictionary *); typedef void (^TPNetFailureBlk)(NSError *); typedef void (^TPNetRequestHeaderBlk)(NSMutableDictionary *); @interface TPNetResqustManager : NSObject @property(nonatomic, copy) TPNetRequestHeaderBlk reqHeaderBlk; @property(nonatomic, copy) NSString *appType; @property(nonatomic, strong, readonly) dispatch_queue_t seriaQueue; (instancetype)shareInstance; (void)postWithUrl:(NSString *)url params:(NSDictionary *)params succeedBlk:(TPNetSucceedBlk)sucBlk failureBlk:(TPNetFailureBlk)failureBlk; (void)getWithUrl:(NSString *)url params:(NSDictionary *)params succeedBlk:(TPNetSucceedBlk)sucBlk failureBlk:(TPNetFailureBlk)failureBlk; (void)postWithUrl:(NSString *)url header:(NSDictionary *)header params:(NSDictionary *)params succeedBlk:(TPNetSucceedBlk)sucBlk failureBlk:(TPNetFailureBlk)failureBlk; (void)getWithUrl:(NSString *)url header:(NSDictionary *)header params:(NSDictionary *)params succeedBlk:(TPNetSucceedBlk)sucBlk failureBlk:(TPNetFailureBlk)failureBlk; @end #import “TPNetResqustManager.h” #import <TPHTTPClient/TPHTTPClient.h> #import <TPHandle-ObjC/TPHandle.h> #import <TPHandle-ObjC/TPGCDReprocessHandle.h> #import <TPHandle-ObjC/TPAbstractHandle.h> #import <TPHTTPClient/TPHTTPResponse.h> #import <TPHTTPClient/TPHTTPResponseConfig.h> #import “TPSecurityPolicy.h” #import “TPNetworkUtil.h” @interface TPNetResqustManager() @property(nonatomic, strong) dispatch_queue_t seriaQueue; @property(nonatomic, strong) NSMutableDictionary *serverDomain; @end static const NSInteger kTPRequestTimeOut = 30; @implementation TPNetResqustManager (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{ NSURLCredential *card = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust]; completionHandler(NSURLSessionAuthChallengeUseCredential,card); } (instancetype)shareInstance { static dispatch_once_t onceToken; static TPNetResqustManager *instance = nil; dispatch_once(&onceToken, ^{ if (instance == nil) { instance = [super allocWithZone:nil]; instance.seriaQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL); instance.serverDomain = [NSMutableDictionary new]; } }); return instance; } (instancetype)allocWithZone:(struct _NSZone *)zone { return [TPNetResqustManager shareInstance]; } #pragma mark - (void)postWithUrl:(NSString *)url params:(NSDictionary *)params succeedBlk:(TPNetSucceedBlk)sucBlk failureBlk:(TPNetFailureBlk)failureBlk { [self postWithUrl:url header:nil params:params succeedBlk:sucBlk failureBlk:failureBlk]; } (void)getWithUrl:(NSString *)url params:(NSDictionary *)params succeedBlk:(TPNetSucceedBlk)sucBlk failureBlk:(TPNetFailureBlk)failureBlk { [self getWithUrl:url header:nil params:params succeedBlk:sucBlk failureBlk:failureBlk]; } (void)postWithUrl:(NSString *)url header:(NSDictionary *)header params:(NSDictionary *)params succeedBlk:(TPNetSucceedBlk)sucBlk failureBlk:(TPNetFailureBlk)failureBlk { [self requstWithUrl:url header:header method:TPHTTPRequestConfigRequestMethodPOST params:params succeedBlk:sucBlk failureBlk:failureBlk]; } (void)getWithUrl:(NSString *)url header:(NSDictionary *)header params:(NSDictionary *)params succeedBlk:(TPNetSucceedBlk)sucBlk failureBlk:(TPNetFailureBlk)failureBlk { [self requstWithUrl:url header:header method:TPHTTPRequestConfigRequestMethodGET params:params succeedBlk:sucBlk failureBlk:failureBlk]; } (void)requstWithUrl:(NSString *)url header:(NSDictionary *)header method:(NSString *)method params:(NSDictionary *)params succeedBlk:(TPNetSucceedBlk)sucBlk failureBlk:(TPNetFailureBlk)failureBlk { TPHTTPRequest *request = [TPHTTPRequest new]; request.timeout = kTPRequestTimeOut; request.httpConfig.url = url; request.httpConfig.method = method; [request.httpConfig.header addEntriesFromDictionary:[TPNetworkUtil defaultHeaders]]; header ? [request.httpConfig.header addEntriesFromDictionary:header] : nil; [TPNetResqustManager shareInstance].reqHeaderBlk ? [TPNetResqustManager shareInstance].reqHeaderBlk(request.httpConfig.header) : nil; #if DEBUG NSLog(@“tprequest:%@ \nheader:%@ \nbody:%@\n”, url, header, params); #endif request.httpConfig.body = params; NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@“tp-link-CA.der”]; // TPHTTPClient *client = [self certClient:path]; TPHTTPClient *client = [self defaultClient]; [TPGCDReprocessHandle reprocessFromHandle:[client sendRequest:request] queue:dispatch_get_main_queue() reprocessAction:^TPHandleResult * _Nullable(TPHandleResult<TPHTTPResponse *> * _Nonnull result) { [client.sessionManager.session finishTasksAndInvalidate]; if (!result.success) { NSDictionary *codeDict = @{ @“httpStatusCode”: @(result.obj.httpConfig.statusCode), @“httpErrorCode”: @(result.obj.httpConfig.urlErrorDomainCode), }; NSMutableDictionary *dict = [NSMutableDictionary new]; dict[@“statusCode”] = codeDict; if (result.obj.httpConfig.body) { dict[@“content”] = result.obj.httpConfig.body; } NSError *err = [NSError errorWithDomain:@"tplink.com" code:1 userInfo:dict]; failureBlk ? failureBlk(err) : nil; return nil; } sucBlk ? sucBlk(result.obj.httpConfig.body) : nil; return nil; }]; } #pragma mark - Private (TPHTTPClient *)defaultClient { return [self certClient:@“”]; } (TPHTTPClient *)certClient:(NSString *)certPath { TPHTTPClient *client = [TPHTTPClient new]; NSMutableSet *types = client.sessionManager.responseSerializer.acceptableContentTypes.mutableCopy; [types addObjectsFromArray:@[@“application/json”, @“text/json”, @“text/javascript”, @“text/html”, @“text/plain”]]; client.sessionManager.responseSerializer.acceptableContentTypes = types; NSData *data = [NSData dataWithContentsOfFile:certPath.length > 0 ? certPath : @“”]; if (data) { AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:[NSSet setWithObject:data]]; policy.allowInvalidCertificates = YES; policy.validatesDomainName = YES; client.sessionManager.securityPolicy = policy; } else { client.sessionManager.securityPolicy = [TPSecurityPolicy defaultPolicy]; } return client; } @end #import <Foundation/Foundation.h> @interface TPNetworkUtil : NSObject (NSDictionary *)defaultHeaders; (NSData *)HMACForData:(NSData *)data withKey:(NSData *)key; (NSString *)strNetSettingForKey:(NSString *)key; @end @interface NSDictionary (Json) (id)jsonValueForKey:(NSString *)key; @end #import “TPNetworkUtil.h” #import <TPHTTPClient/TPHTTPRequest.h> //#import <TPFoundation/TPFoundation.h> #import <Foundation/Foundation.h> #import <CommonCrypto/CommonDigest.h> #include <CommonCrypto/CommonHMAC.h> #import “TPNetResqustManager.h” static const NSString * const kTPNetRequestHeaderContentTypeKey = @“Content-Type”; @implementation TPNetworkUtil (NSDictionary *)defaultHeaders { NSMutableDictionary *dict = [NSMutableDictionary new]; dict[kTPNetRequestHeaderContentTypeKey] = @“application/json”; return dict; } (NSData *)HMACForData:(NSData *)data withKey:(NSData *)key { if (key.length <= 0 || data.length <= 0) { return nil; } NSMutableData* hmac = [NSMutableData dataWithLength:CC_SHA1_DIGEST_LENGTH]; CCHmac(kCCHmacAlgSHA1, key.bytes, key.length, data.bytes, data.length, hmac.mutableBytes); return hmac.copy; } (NSString *)strNetSettingForKey:(NSString *)key { return [self netSettingForKey:key]; } (id)netSettingForKey:(NSString *)key { static NSDictionary *setting = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ setting = [self envirenment]; }); if (setting == nil) { setting = [self envirenment]; } if (key.length == 0) { return nil; } #if BETA_EXPORT_SALE_CLOUD key = [NSString stringWithFormat:@“%@.beta”,key]; #else key = [NSString stringWithFormat:@“%@.release”, key]; #endif return [setting jsonValueForKey:key]; } #pragma mark - Private (NSDictionary *)envirenment { NSString *filePath = [[NSBundle mainBundle] pathForResource:@“VIGIAPPConfig” ofType:@“json”]; NSData *data = [NSData dataWithContentsOfFile:filePath]; if (data) { NSError *error; id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; return jsonObject != nil ? jsonObject : @{}; } return @{}; } @end @implementation NSDictionary (Json) (id)jsonValueForKey:(NSString *)key { NSArray *keys = [key componentsSeparatedByString:@“.”]; NSDictionary *value = self; for (NSString *key in keys) { if (![value isKindOfClass:[NSDictionary class]]) { return nil; } value = [value valueForKey:key]; } return value; } @end #import <AFNetworking/AFNetworking.h> @interface TPSecurityPolicy : AFSecurityPolicy @end #import “TPSecurityPolicy.h” @implementation TPSecurityPolicy (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust forDomain:(NSString *)domain { NSString *tmp = [domain.lowercaseString stringByReplacingOccurrencesOfString:@“_” withString:@“”]; tmp = [tmp stringByReplacingOccurrencesOfString:@“-” withString:@“”]; if ([tmp containsString:@“tplink”]) { return YES; } return [super evaluateServerTrust:serverTrust forDomain:domain]; } @end 这六个文件实现了一个完整的模块,实现了什么功能?用swift写一个类,通过上面的架构实现下面这个接口请求:curl --location 'https://n-aps1-device-api.i.tplinkcloud.com/v1/firmware/batchGetSecureFwList?model=default&hwId=47C26D2BF192B61BBC0303A9BF0F75CD&hwVer=1.0&oemId=9BF735F1FB702AE2AF540201276E5063&fwVer=1.2.9&deviceType=CDD.PC.CLIENTSOFTWARE&user=default&deviceId=default&deviceToken=default' --header 'Content-Type: application/json' --header 'Cookie: SameSite=Lax' --data '{ "queryList": [ { "hwId": "47C26D2BF192B61BBC0303A9BF0F75CD", "oemId": "9BF735F1FB702AE2AF540201276E5063", "currentFwVer": "1.2.0", "fwId": "", "locale": "en_US" } ], "bizId": "xxx" }'
最新发布
12-16
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值