1
所以我有這個問題,一旦NSFileHandle/NSPipe被觸發......我的CPU使用和內存開始瘋狂。問題是我發現很難找到這個泄漏。任何意見或幫助表示讚賞。乾杯。有人可以幫我找到這個NSPipe/NSFileHandle代碼泄漏嗎?
.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];
}
}
您可能會考慮用[可讀性處理程序塊]替換基於NSNotification的代碼(http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSFileHandle_Class/Reference/Reference。 HTML#// apple_ref/OCC/instp/NSFileHandle/readabilityHandler)。至於資源消耗問題,請在「工具」下運行您的應用程序,使用Time Profiler來分析CPU使用情況以及泄漏模板以剖析內存使用情況。 – 2012-07-30 07:54:38
感謝關於可讀性處理程序塊的提示。我會詳細閱讀。我用儀器進行了相當多的測試,這是我知道我有這個問題......但我似乎無法追查我做錯了什麼。再次感謝。 – crewshin 2012-07-30 16:55:35
時間分析器和分配工具都提供一個調用樹,顯示程序的每個部分(包括框架代碼)正在使用多少時間/內存。泄漏儀器會給你一個每個泄漏物體的清單(不包括你仍然持有但未使用的「遺棄」物體)。 – 2012-07-30 17:59:26