-->

有人可以帮我找出这个NSPipe / NSFileHandle代码泄漏?(Can someone h

2019-10-17 02:12发布

所以我有这个问题,即一旦该NSFileHandle / NSPipe被触发...我的CPU使用率和内存开始快要疯了。 问题是,我发现很难找到这种泄漏。 任何意见或帮助表示赞赏。 干杯。

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

Answer 1:

我在使用readabilityHandler遇到了类似的问题。 我终于找出关闭文件句柄后任务完成解决该问题。 希望它可以帮助你的情况。



文章来源: Can someone help me spot a leak in this NSPipe/NSFileHandle code?