gpt4 book ai didi

iOS 如何限制 ASIHTTPRequest 并发连接数?

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

我正在开发一个 RSS 阅读器,它使用 ASIHTTPRequest 异步下载每个提要的帖子。

在初始运行期间,大量连接同时发生,即使我使用 3-MOC 解决方案(用于写入的专用 -> 用于 UI 的主 -> 用于数据编辑的专用),它似乎也会卡住 UI。

我想知道如何限制 ASIHTTPRequest 类,将其同时连接数限制为...2 或 4,而不是(我在调试器中看到)一次连接数十个。

最佳答案

使用您自己创建的 ASINetworkQueue 可以让您更好地控制异步请求。使用队列时,只能同时运行一定数量的请求。如果您添加的请求多于队列的 maxConcurrentOperationCount 属性,请求将在开始之前等待其他请求完成。

显示如何使用 ASIHTTPRequest 管理队列的示例:

#import <Foundation/Foundation.h>
#import <GHUnit/GHUnit.h>
@class ASINetworkQueue;

@interface MyController : NSObject {
ASINetworkQueue *networkQueue;

}

- (void)doNetworkOperations;

@property (retain) ASINetworkQueue *networkQueue;

@end

-------------------------------------------------------------------

#import "MyController.h"
#import "ASIHTTPRequest.h"
#import "ASINetworkQueue.h"

@implementation MyController

- (void)dealloc
{
[networkQueue release];
[super dealloc];
}

- (void)doNetworkOperations
{
// Stop anything already in the queue before removing it
[[self networkQueue] cancelAllOperations];

// Creating a new queue each time we use it means we don't have to worry about clearing delegates or resetting progress tracking
[self setNetworkQueue:[ASINetworkQueue queue]];
[[self networkQueue] setDelegate:self];
[[self networkQueue] setRequestDidFinishSelector:@selector(requestFinished:)];
[[self networkQueue] setRequestDidFailSelector:@selector(requestFailed:)];
[[self networkQueue] setQueueDidFinishSelector:@selector(queueFinished:)];

int i;
for (i=0; i<5; i++) {
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com"]];
[[self networkQueue] addOperation:request];
}

[[self networkQueue] go];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
// You could release the queue here if you wanted
if ([[self networkQueue] requestsCount] == 0) {

// Since this is a retained property, setting it to nil will release it
// This is the safest way to handle releasing things - most of the time you only ever need to release in your accessors
// And if you an Objective-C 2.0 property for the queue (as in this example) the accessor is generated automatically for you
[self setNetworkQueue:nil];
}

//... Handle success
NSLog(@"Request finished");
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
// You could release the queue here if you wanted
if ([[self networkQueue] requestsCount] == 0) {
[self setNetworkQueue:nil];
}

//... Handle failure
NSLog(@"Request failed");
}


- (void)queueFinished:(ASINetworkQueue *)queue
{
// You could release the queue here if you wanted
if ([[self networkQueue] requestsCount] == 0) {
[self setNetworkQueue:nil];
}
NSLog(@"Queue finished");
}

@synthesize networkQueue;
@end

关于iOS 如何限制 ASIHTTPRequest 并发连接数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20324622/

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