gpt4 book ai didi

objective-c - 有人可以帮我发现这个 NSPipe/NSFileHandle 代码中的泄漏吗?

转载 作者:行者123 更新时间:2023-12-03 17:14:12 25 4
gpt4 key购买 nike

所以我遇到了这个问题,一旦这个 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];
}
}

最佳答案

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

关于objective-c - 有人可以帮我发现这个 NSPipe/NSFileHandle 代码中的泄漏吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11713744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com