gpt4 book ai didi

objective-c - NSURLConnectionDelegate 静态类包装器不调用函数调用 (ARC)

转载 作者:行者123 更新时间:2023-11-29 11:11:05 25 4
gpt4 key购买 nike

我正在尝试为我的 iOS 应用程序组合一个静态类,它将封装我的 HTTP 通信逻辑。我知道如何通过 + 符号在 Objective-C 中创建静态方法,但我想让我的类能够接受一个 block 并在任务完成时调用它。到目前为止,我得到的类编译得很好,但是当我调用它的函数时,它只会到达某个点而失败。这是我当前的代码:

#import <UIKit/UIKit.h>

#pragma mark - Globals
#import "Globals.h"

@interface HTTPRequest : NSObject <NSURLConnectionDelegate>
+ (void)GET:(NSMutableURLRequest *)request completionBlock:(void (^)(void))block;
+ (void)POST:(NSMutableURLRequest *)request andBody:(NSString *)requestString completionBlock:(void (^)(void))block;
@end

#import "HTTPRequest.h"

@interface HTTPRequest () {
NSInteger statusCode;
}
@end

static void (^completionBlock)(void);

@implementation HTTPRequest
+ (void)GET:(NSMutableURLRequest *)request completionBlock:(void (^)(void))block {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

[request setHTTPMethod:@"GET"];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];

if (connection) {
responseData = [[NSMutableData alloc] init];
} else {
NSLog(@"NSURLConnection INSTANCE FAILED");
};

completionBlock = block;
}

+ (void)POST:(NSMutableURLRequest *)request andBody:(NSString *)requestString completionBlock:(void (^)(void))block {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

NSData *requestData = [NSData dataWithBytes:[requestString UTF8String]
length:[requestString length]];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPBody:requestData];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];

if (connection) {
responseData = [[NSMutableData alloc] init];
} else {
NSLog(@"NSURLConnection INSTANCE FAILED");
};

completionBlock = block;
}

#pragma mark - NSURLConnectionDelegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];

statusCode = [((NSHTTPURLResponse *)response) statusCode];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"CONNECTION ERROR: %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"RESPONSE STRING: %@", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

if (statusCode == 200) {
completionBlock();
} else {
NSLog(@"RESPONSE ERROR: %i", statusCode);
};
}
@end

我知道 GET 和 POST 函数被调用并且它们创建了 NSURLConnection 对象。此后,不会调用任何 NSURLConnectionDelegate 函数。

任何人都可以发现问题,或者,如果我的做法完全错误,请告诉我。提前致谢!

更新

我应该指出该应用程序是基于 ARC 的。我在这里阅读了关于未调用 NSURLConnectionDelegate 函数的其他问题,但大多数问题似乎是因为开发人员将对象设置为 autorelease。由于我无法控制它,所以我认为这应该不是问题。

更新 2(重写?)

我做了一些更改,从静态函数创建类的实例并使用它的实例函数。现在调用了 NSURLConnectionDelegate 函数,我知道我的 onSuccessBlock block 也被调用了,所以整个类一直在执行。坦率地说,我不确定这是否是合法的代码,但编译器没有提示,我看到了我期待的日志消息,所以我会接受它。这是当前的实现:

#import <UIKit/UIKit.h>

@interface HTTPRequest : NSObject <NSURLConnectionDelegate>
+ (void)requestAsGET:(NSMutableURLRequest *)request onSuccess:(void (^)(void))successBlock onFail:(void (^)(void))failBlock;
- (void)requestAsGET:(NSMutableURLRequest *)request onSuccess:(void (^)(void))successBlock onFail:(void (^)(void))failBlock;
+ (void)requestAsPOST:(NSMutableURLRequest *)request body:(NSString *)body onSuccess:(void (^)(void))successBlock onFail:(void (^)(void))failBlock;
- (void)requestAsPOST:(NSMutableURLRequest *)request body:(NSString *)body onSuccess:(void (^)(void))successBlock onFail:(void (^)(void))failBlock;
@end

#import "HTTPRequest.h"

@interface HTTPRequest () {
NSMutableData *responseData;
NSInteger statusCode;

void (^onSuccessBlock)(void);
void (^onFailBlock)(void);
}
@end

@implementation HTTPRequest
- (id)init {
self = [super init];

if (self) {
};

return self;
}

+ (void)requestAsGET:(NSMutableURLRequest *)request onSuccess:(void (^)(void))successBlock onFail:(void (^)(void))failBlock {
[[[HTTPRequest alloc] init] requestAsGET:request
onSuccess:successBlock
onFail:failBlock];
}

- (void)requestAsGET:(NSMutableURLRequest *)request onSuccess:(void (^)(void))successBlock onFail:(void (^)(void))failBlock {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

[request setHTTPMethod:@"GET"];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];

if (connection) {
onSuccessBlock = successBlock;
onFailBlock = failBlock;
} else {
NSLog(@"NSURLConnection INSTANCE FAILED");
};
}

+ (void)requestAsPOST:(NSMutableURLRequest *)request body:(NSString *)body onSuccess:(void (^)(void))successBlock onFail:(void (^)(void))failBlock {
[[[HTTPRequest alloc] init] requestAsPOST:request
body:body
onSuccess:successBlock
onFail:failBlock];
}

- (void)requestAsPOST:(NSMutableURLRequest *)request body:(NSString *)body onSuccess:(void (^)(void))successBlock onFail:(void (^)(void))failBlock {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

NSData *requestData = [NSData dataWithBytes:[body UTF8String]
length:[body length]];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPBody:requestData];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];

if (connection) {
onSuccessBlock = successBlock;
onFailBlock = failBlock;
} else {
NSLog(@"NSURLConnection INSTANCE FAILED");
};
}

#pragma mark - NSURLConnectionDelegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];

statusCode = [((NSHTTPURLResponse *)response) statusCode];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"CONNECTION ERROR: %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"RESPONSE STRING: %@", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

if (statusCode == 200) {
// Pass responseData into the block... How?

onSuccessBlock();
} else {
// Pass statusCode into the block?

onFailBlock();
};
}
@end

最佳答案

我会使用单例模式而不是静态类。这样您就不必担心另一个请求会覆盖前一个请求的数据。

以您的 NSMutableData responseData 为例。您将需要一个实例变量来通过连接生命周期跟踪该数据。我没有看到一个,但如果你有一个,你需要确保没有其他连接可以更新它。这意味着您不能将其设为静态变量,这可能是您的初始 react 。

无论采用哪种方式,您都应该将 responseData 变量放入以 NSUrlConnection 为键的字典中。这样,在每个委托(delegate)方法实现上,您都可以从连接中查找数据并执行任何您需要的操作。

所以在这种情况下你可以这样做:

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];

if (connection) {
responseData = [[NSMutableData alloc] init];

// So this would be a NSMutableDictionary you would store your connection in
[requests setValue:responseData forKey:connection];

} else {
NSLog(@"NSURLConnection INSTANCE FAILED");
};

然后你可以在你的委托(delegate)方法中这样做

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSMutableData *responseData = [requests valueForKey:connection];

[responseData appendData:data];
}

对于我个人的实现,我选择使用 CFMutableDictionaryRef 而不是 NSMutableDictionary,因为我相信 NSMutableDictionary 不会保留添加到其中的对象。我的代码是在 ARC 之前编写的,因此您可能不必担心。如果您尝试此方法并开始获取 EXC_BAD_ACCESS 或遇到内存问题,请使用 CFMutableDictionaryRef。

希望这能让您朝着正确的方向前进。你的头绝对是在正确的地方:)

基于重写

所以让我尝试根据您的重写更好地解释我上面提到的内容:

- (void)requestAsGET:(NSMutableURLRequest *)request onSuccess:(void (^)(void))successBlock onFail:(void (^)(void))failBlock {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

[request setHTTPMethod:@"GET"];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];

if (connection) {

/** This is your problem. You are trying to save data to some instance variables
but there's a data integrity issue here. If you fire off two requests, the
second request will overwrite these two values which would, at the time, contain
information from the first request */

onSuccessBlock = successBlock;
onFailBlock = failBlock;

} else {
NSLog(@"NSURLConnection INSTANCE FAILED");
};
}

所以你在第一步就遇到了设计问题,在你解决这个问题之前,接下来发生的事情真的无关紧要。我的建议是使用当前的 NSURLConnection 作为键将您的 ** HTTPRequest** 值对象保存到字典中。这样,在每个委托(delegate)方法上,您都可以查找特定于该连接的数据并对其进行修改,而不必担心其他请求会影响您的数据。

像这样:

if (connection) {

// Store the data in an object... call it whatever you want
SomeObject *someObject = [[SomeObject all] init];
someObject.responseData = [[NSMutableData alloc] init];
someObject.onSuccessBlock = successBlock;
someObject.onFailBlock = failBlock;

/** Have an NSMutableDictionary that stores all the value objects
under the corresponding connection since ALL NSURLConnectionDelegate
methods include a reference to the NSURLConnection for the request */
[requests setValue:someObject forKey:connection];

} else {
NSLog(@"NSURLConnection INSTANCE FAILED");
};

关于objective-c - NSURLConnectionDelegate 静态类包装器不调用函数调用 (ARC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11572831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com