有人可以帮助我在此NSPipe/NSFileHandle代码中发现泄漏吗? [英] Can someone help me spot a leak in this NSPipe/NSFileHandle code?

查看:107
本文介绍了有人可以帮助我在此NSPipe/NSFileHandle代码中发现泄漏吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我遇到了这个问题,一旦这个NSFileHandle/NSPipe被触发...我的CPU使用率和内存开始发疯.问题是我发现很难找到此泄漏.任何建议或帮助,不胜感激.干杯.

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];
    }
}

推荐答案

在使用readabilityHandler时遇到了类似的问题.我终于发现在任务完成后关闭了fileHandle可以解决问题.希望对您有帮助.

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.

这篇关于有人可以帮助我在此NSPipe/NSFileHandle代码中发现泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆