English 中文(简体)
1. 简化国家情报和安全局
原标题:Streaming NSXMLParser with NSInputStream

<>Update:

使用<条码>NSXMLParser 班级方法initWithContentsOfURL,而不是像XML(XML)的饲料被下载一样,似乎试图将全部XML的档案装上记忆中,然后才启动教区程序。 如果XML的饲料量很大(使用过多的RAM,其内在效率不高,因为与下载相比,它只是从下载开始。

是否有任何人发现在用将饲料流到装置中时如何 par? 是的,你可以使用<代码>LibXML2(如下文所述),但似乎可以使用。 但是,这 me了我。

www.un.org/Depts/DGACM/index_spanish.htm

我正在使用NSXParser 改为XML,从一个网络流。 如果你使用,,而接口则从该接口到X中可使用。 对于规模不大的XML文件来说,这会造成问题,但对于实际规模很大的罚款。

。 例如,有人对此作了答复,建议使用诸如等内容。 rel=“noreferer”>following Kora Buildinger post;NSInputStream,该编码使用了 rel=“诺referer”NSURLConnection<。 (这本身就是流利),但我有幸能够与合作。

最后,我决定使用LibXML2。 http://developer.apple.com/library/ios/#samplecode/XMLPerformance/Introduction/Intro.html” rel=“noreferer”>XMLPerformance samples,但我想知道是否有任何幸运的人从一个网络来源中流出,从事以下编码:NSXParser/code。 http://developer.apple.com/library/ios/documents/

Ray Wenderlich article 选择最佳XML Parser似乎证实,NSXMLPars并不适合大型XML文档,但所有员额都可能使用NSXMLParser,以工作------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 是否有任何人了解网络上流出的运行中的<代码>NSXMLParser执行? 显然,我只能遵守<代码>LibXML2。 或者其他一些类似的XML教区,但与<条码>NSXMLParser合并的概念似乎已接近尾声。

最佳回答

<代码>-[NSXMLParser initWithStream:]是目前进行数据流层的唯一接口NSXMLParser。 Hooking it up to an asynchronous NSURLConnection that s provision datamentally is unwieldy on NSXMLParser 采用一种从<代码>NSInputStream上读取的阻挡、“费”方法。 也就是说,-[NSXMLParser parse]在处理时,采取下列做法: NSInputStream:

while (1) {
    NSInteger length = [stream read:buffer maxLength:maxLength];
    if (!length)
        break;

    // Parse data …
}

为逐步向下层提供数据,需要一个门槛值(<0>NSInputStream)的子流体,即:接收的单体数据需要一个背景点,或向查询。 电话NSXMLParser正在等待。

概念证据执行如下:

#include <Foundation/Foundation.h>

@interface ReceivedDataStream : NSInputStream <NSURLConnectionDelegate>
@property (retain) NSURLConnection *connection;
@property (retain) NSMutableArray *bufferedData;
@property (assign, getter=isFinished) BOOL finished;
@property (retain) dispatch_semaphore_t semaphore;
@end

@implementation ReceivedDataStream

- (id)initWithContentsOfURL:(NSURL *)url
{
    if (!(self = [super init]))
        return nil;

    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    self.connection = [[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO] autorelease];
    self.connection.delegateQueue = [[[NSOperationQueue alloc] init] autorelease];
    self.bufferedData = [NSMutableArray array];
    self.semaphore = dispatch_semaphore_create(0);

    return self;
}

- (void)dealloc
{
    self.connection = nil;
    self.bufferedData = nil;
    self.semaphore = nil;

    [super dealloc];
}

- (BOOL)hasBufferedData
{
    @synchronized (self) { return self.bufferedData.count > 0; }
}

#pragma mark - NSInputStream overrides

- (void)open
{
    NSLog(@"open");
    [self.connection start];
}

- (void)close
{
    NSLog(@"close");
    [self.connection cancel];
}

- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)maxLength
{
    NSLog(@"read:%p maxLength:%ld", buffer, maxLength);
    if (self.isFinished && !self.hasBufferedData)
        return 0;

    if (!self.hasBufferedData)
        dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);

    NSAssert(self.isFinished || self.hasBufferedData, @"Was woken without new information");

    if (self.isFinished && !self.hasBufferedData)
        return 0;

    NSData *data = nil;
    @synchronized (self) {
        data = [[self.bufferedData[0] retain] autorelease];
        [self.bufferedData removeObjectAtIndex:0];
        if (data.length > maxLength) {
            NSData *remainingData = [NSData dataWithBytes:data.bytes + maxLength length:data.length - maxLength];
            [self.bufferedData insertObject:remainingData atIndex:0];
        }
    }

    NSUInteger copiedLength = MIN([data length], maxLength);
    memcpy(buffer, [data bytes], copiedLength);
    return copiedLength;
}


#pragma mark - NSURLConnetionDelegate methods

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"connection:%@ didReceiveData:…", connection);
    @synchronized (self) {
        [self.bufferedData addObject:data];
    }
    dispatch_semaphore_signal(self.semaphore);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"connectionDidFinishLoading:%@", connection);
    self.finished = YES;
    dispatch_semaphore_signal(self.semaphore);
}

@end

@interface ParserDelegate : NSObject <NSXMLParserDelegate>
@end

@implementation ParserDelegate

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
    NSLog(@"parser:%@ didStartElement:%@ namespaceURI:%@ qualifiedName:%@ attributes:%@", parser, elementName, namespaceURI, qualifiedName, attributeDict);
}

- (void)parserDidEndDocument:(NSXMLParser *)parser
{
    NSLog(@"parserDidEndDocument:%@", parser);
    CFRunLoopStop(CFRunLoopGetCurrent());
}

@end


int main(int argc, char **argv)
{
    @autoreleasepool {

        NSURL *url = [NSURL URLWithString:@"http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xml"];
        ReceivedDataStream *stream = [[ReceivedDataStream alloc] initWithContentsOfURL:url];
        NSXMLParser *parser = [[NSXMLParser alloc] initWithStream:stream];
        parser.delegate = [[[ParserDelegate alloc] init] autorelease];

        [parser performSelector:@selector(parse) withObject:nil afterDelay:0.0];

        CFRunLoopRun();

    }
    return 0;
}
问题回答

我注意到布达什的回答使用了NSURLConnection。 但是,根据NSURLConnection Documentation

这份年度清单被认为是遗产。 而是使用NSURLSession。

因此,我改为NSURLSessionDataTask。

#import <Foundation/Foundation.h>
#import <objc/objc-sync.h>

@interface RemoteInputStream : NSInputStream
+ (instancetype)new NS_UNAVAILABLE;
+ (instancetype)inputStreamWithData:(NSData *)data NS_UNAVAILABLE;
+ (instancetype)inputStreamWithFileAtPath:(NSString *)path NS_UNAVAILABLE;
- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithData:(NSData *)data NS_UNAVAILABLE;
- (instancetype)initWithFileAtPath:(NSString *)path NS_UNAVAILABLE;

+ (instancetype)inputStreamWithRequest:(NSURLRequest *)request;
- (instancetype)initWithRequest:(NSURLRequest *)request NS_DESIGNATED_INITIALIZER;
@end

@interface RemoteInputStream () <NSURLSessionDataDelegate>
@property (retain) NSURLSessionDataTask *sessionDataTask;
@property (retain) NSMutableArray<NSData *> *bufferData;
@property (retain, nullable) dispatch_semaphore_t semaphore;
@end

@implementation RemoteInputStream

+ (instancetype)inputStreamWithRequest:(NSURLRequest *)request {
    return [[[self.class alloc] initWithRequest:request] autorelease];
}

- (instancetype)initWithURL:(NSURL *)url {
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    self = [self initWithRequest:request];
    [request release];
    return self;
}

- (instancetype)initWithRequest:(NSURLRequest *)request {
    if (self = [super initWithURL:request.URL]) {
        NSURLSession *session = [NSURLSession sessionWithConfiguration:NSURLSessionConfiguration.ephemeralSessionConfiguration];
        NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request];
        self.sessionDataTask = sessionDataTask;
        
        NSMutableArray<NSData *> *bufferData = [NSMutableArray<NSData *> new];
        self.bufferData = bufferData;
        [bufferData release];
    }
    
    return self;
}

- (void)dealloc {
    [_sessionDataTask cancel];
    [_sessionDataTask release];
    [_bufferData release];
    
    if (_semaphore) {
        dispatch_release(_semaphore);
    }
    
    [super dealloc];
}

- (void)open {
    self.sessionDataTask.delegate = self;
    [self.sessionDataTask resume];
}

- (void)close {
    self.sessionDataTask.delegate = nil;
    [self.sessionDataTask suspend];
}

- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len {
    objc_sync_enter(self);
    
    if (self.bufferData.count == 0) {
        if (self.sessionDataTask.state == NSURLSessionTaskStateRunning) {
            dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
            self.semaphore = semaphore;
            
            objc_sync_exit(self);
            
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            objc_sync_enter(self);
            
            self.semaphore = nil;
            dispatch_release(semaphore);
            
            if (self.bufferData.count == 0) {
                objc_sync_exit(self);
                return 0;
            }
        } else {
            objc_sync_exit(self);
            return 0;
        }
    }
    
    NSMutableData *result = [NSMutableData new];
    NSUInteger remaining = len;
    
    while (YES) {
        NSAutoreleasePool *pool = [NSAutoreleasePool new];
        
        BOOL shouldBreak;
        
        if (remaining < self.bufferData[0].length) {
            NSData *data1 = [self.bufferData[0] subdataWithRange:NSMakeRange(0, remaining)];
            NSData *data2 = [self.bufferData[0] subdataWithRange:NSMakeRange(remaining, self.bufferData[0].length - remaining)];
            
            [result appendData:data1];
            [self.bufferData replaceObjectAtIndex:0 withObject:data2];
            remaining = 0;
            shouldBreak = YES;
        } else {
            [result appendData:self.bufferData[0]];
            remaining -= self.bufferData[0].length;
            [self.bufferData removeObjectAtIndex:0];
            
            if (self.bufferData.count == 0) {
                shouldBreak = YES;
            } else {
                shouldBreak = NO;
            }
        }
        
        [pool release];
        
        if (remaining == 0) {
            shouldBreak = YES;
        }
        
        if (shouldBreak) {
            break;
        }
    }
    
    objc_sync_exit(self);
    
    NSUInteger length = result.length;
    
    memcpy(buffer, result.bytes, length);
    [result release];
    
    return length;
}

#pragma mark - NSURLSessionDataDelegate

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    objc_sync_enter(self);
    [self.bufferData addObject:data];
    
    if (self.semaphore) {
        dispatch_semaphore_signal(self.semaphore);
    }
    
    objc_sync_exit(self);
}

@end

单位测试守则实例:

#import <XCTest/XCTestCase.h>

@interface RemoteInputStreamTests : XCTestCase
@end

@implementation RemoteInputStreamTests

- (void)test_read {
    NSURL *testURL = [NSURL URLWithString:@"https://fastly.picsum.photos/id/11/2500/1667.jpg?hmac=xxjFJtAPgshYkysU_aqx2sZir-kIOjNR9vx0te7GycQ"];
    NSData *normalData = [NSData dataWithContentsOfURL:testURL];
    
    RemoteInputStream *inputStream = [RemoteInputStream inputStreamWithURL:testURL];
    [inputStream open];
    
    NSUInteger maxLength = 16;
    uint8_t *buffer = malloc(sizeof(uint8_t) * maxLength);
    NSUInteger len = [inputStream read:buffer maxLength:maxLength];
    NSMutableData *streamingData = [NSMutableData new];
    
    while (len) {
        [streamingData appendBytes:buffer length:len];
        len = [inputStream read:buffer maxLength:maxLength];
    }
    
    free(buffer);
    
    XCTAssertTrue([normalData isEqualToData:streamingData]);
    
    [streamingData release];
}

@end




相关问题
List Contents of Directory in a UITableView

I am trying to list the contents of Ringtones directory in a TableView, however, I am only getting the last file in the directory in ALL cells, instead of file per cell. This is my code: - (...

iPhone NSUserDefaults persistance difficulty

In my app i have a bunch of data i store in the NSUserdefaults. This information consists of an NSObject (Object1) with NSStrings and NSNumbers and also 2 instances of yet another object (Object2). ...

Writing a masked image to disk as a PNG file

Basically I m downloading images off of a webserver and then caching them to the disk, but before I do so I want to mask them. I m using the masking code everyone seems to point at which can be found ...

Resize UIImage with aspect ratio?

I m using this code to resize an image on the iPhone: CGRect screenRect = CGRectMake(0, 0, 320.0, 480.0); UIGraphicsBeginImageContext(screenRect.size); [value drawInRect:screenRect blendMode:...

Allowing interaction with a UIView under another UIView

Is there a simple way of allowing interaction with a button in a UIView that lies under another UIView - where there are no actual objects from the top UIView on top of the button? For instance, ...

热门标签