Can someone help me spot a leak in this NSPipe/NSFileHandle code?

我的未来我决定 提交于 2019-12-11 10:59:50

问题


So I'm having this issue where once this NSFileHandle/NSPipe gets triggered... my CPU use and memory start going crazy. Problem is I'm finding it hard to find this leak. Any advice or help is appreciated. Cheers.

.h

NSTask *task;
NSPipe *pipe;
NSFileHandle *fileHandle;

@property (weak) IBOutlet NSTextField *commandInputTextField;
@property (unsafe_unretained) IBOutlet NSTextView *nsTastOutput;
@property (weak) IBOutlet NSButton *useOutputSwitch;

.m

- (id)init
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(readPipe:)
                                             name:NSFileHandleReadCompletionNotification
                                           object:nil];
}

- (void)tasker
{   
    task = [[NSTask alloc] init];

    [task setLaunchPath:@"/bin/bash"];

    NSArray *argumentBuilder = [[_commandInputTextField stringValue] componentsSeparatedByString:@" "];

    [task setArguments:argumentBuilder];

    // Pipe output to ScrollView
    if (_useOutputSwitch.state == YES)
    {
        if (!pipe)
        {
            pipe = [[NSPipe alloc] init];
        }

        fileHandle = [pipe fileHandleForReading];
        [fileHandle readInBackgroundAndNotify];

        [task setStandardOutput:pipe];
        [task setStandardError:pipe];
    }

    // Launch task
    [task launch];
}


- (void)readPipe:(NSNotification *)notification
{
    NSData *data;
    NSString *text;

    if( [notification object] != fileHandle )
    {
        return;
    }

    data = [[notification userInfo] objectForKey:NSFileHandleNotificationDataItem];
    text = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

    NSScroller *scroller = [[_nsTastOutput enclosingScrollView] verticalScroller];
    BOOL shouldScrollToBottom = [scroller doubleValue] == 1.0;
    NSTextStorage *ts = [_nsTastOutput textStorage];
    [ts replaceCharactersInRange:NSMakeRange([ts length], 0) withString:text];
    if (shouldScrollToBottom)
    {
        NSRect bounds = [_nsTastOutput bounds];
        [_nsTastOutput scrollPoint:NSMakePoint(NSMaxX(bounds), NSMaxY(bounds))];
    }

    if (data != 0)
    {
        [fileHandle readInBackgroundAndNotify];
    }
}

回答1:


I met a similar problem while using the readabilityHandler. I finally find out closing the fileHandle after task complete resolves the problem. Wish it helps your case.



来源:https://stackoverflow.com/questions/11713744/can-someone-help-me-spot-a-leak-in-this-nspipe-nsfilehandle-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!