NSStream выпущен во время чтения, EXC_BAD_ACCESS iPhone SDK

У меня есть контроллер представления, который является NSStreamDelegate, у меня проблема, когда представление выталкивается из контроллера навигации во время потоковой передачи, я получаю сообщение об ошибке «EXC_BAD_ACCESS». Я попытался закрыть поток, но, похоже, это не останавливает его, если поток выполняется. Каков правильный способ справиться с этим, можете ли вы отложить просмотр, если что-то транслируется?

#import "CameraViewer.h"

@implementation CameraViewer
@synthesize camService;
@synthesize currentDownload;

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil theService:(NSNetService *)cameraService {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
        [self setCamService:cameraService];
    }
    return self;
}



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    [self downloadAgain];
}

- (void)viewWillDisappear:(BOOL)animated{
    NSLog(@"view is going away");
    NSInputStream *istream;
    [camService getInputStream:&istream outputStream:nil];
    [istream close];
    NSLog(@"view is gone");
    [super viewWillDisappear:animated];
}


- (void)downloadAgain{
        NSInputStream *istream;
        [camService getInputStream:&istream outputStream:nil];
        [istream retain];
        [istream setDelegate:self];
        [istream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [istream open];
}

#pragma mark NSStream delegate method

- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)event {
        switch(event) {
            case NSStreamEventHasBytesAvailable:
                NSLog(@"Reading Stream");
                if (![self currentDownload]) {
                    [self setCurrentDownload:[[NSMutableData alloc] initWithCapacity:409600]];
                }
                uint8_t readBuffer[4096];
                int amountRead = 0;
                NSInputStream * is = (NSInputStream *)aStream;
                amountRead = [is read:readBuffer maxLength:4096];
                [[self currentDownload] appendBytes:readBuffer length:amountRead];
                //NSLog(@"case 1");
                break;
            case NSStreamEventEndEncountered:
                [(NSInputStream *)aStream close];
                UIImage *newImage = [[UIImage alloc] initWithData:[self currentDownload]];
                [self setCurrentDownload:nil];
                if(newImage != nil){
                    [imageView setImage:newImage];
                }
                [newImage release];
                [self performSelector:@selector(downloadAgain) withObject:nil afterDelay:0.25];
                break;
            default:
                break;
        }
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [[self camService] release];
    [[self currentDownload] release];
    [super dealloc];
}


@end

person Matt    schedule 18.10.2010    source источник


Ответы (2)


Я вижу, вы звоните scheduleInRunLoop. В том случае, когда вам не нужен поток, вы также должны вызвать

[istream removeFromRunLoop:[NSRunLoop currentRunLoop] 
                   forMode: NSDefaultRunLoopMode];

после закрытия потока.

person Nicu Surdu    schedule 13.04.2012

Происходит то, что любой экземпляр класса CameraViewer (который настроен как делегат) освобождается (вызывая EXC_BAD_ACCESS в цикле выполнения), потому что вы его не сохранили.

Решение состоит в том, чтобы либо сохранить вызов класса CameraViewer при создании экземпляра, например:

CameraViewer *cameraViewer = [[CameraViewer alloc] init];
[cameraViewer retain];
person arjunyg    schedule 27.05.2013