NSAppleScript 泄漏大量内存
我有以下类方法来执行 AppleScript:
+ (NSString *) executeAppleScript:(NSString *) scriptToRun{
NSAutoreleasePool *thePool = [[NSAutoreleasePool alloc] init];
NSAppleScript *appleScriptObject = [[NSAppleScript alloc] initWithSource:scriptToRun];
NSAppleEventDescriptor *objectReturned = [appleScriptObject executeAndReturnError:nil];
[appleScriptObject release];
appleScriptObject = nil;
NSString *charToReturn = [objectReturned stringValue];
if (charToReturn == nil ){
charToReturn = [NSString stringWithString:@"error"];
}
[charToReturn retain];
[thePool drain];
[charToReturn autorelease];
return charToReturn;
}
问题是,这泄漏了大量内存。我完全承认我并不完全理解 Cocoa 中的内存分配,所以我希望有人能够向我解释为什么即使使用自动释放池也会如此泄漏。
非常感谢任何帮助。
I have the following class method to execute an AppleScript:
+ (NSString *) executeAppleScript:(NSString *) scriptToRun{
NSAutoreleasePool *thePool = [[NSAutoreleasePool alloc] init];
NSAppleScript *appleScriptObject = [[NSAppleScript alloc] initWithSource:scriptToRun];
NSAppleEventDescriptor *objectReturned = [appleScriptObject executeAndReturnError:nil];
[appleScriptObject release];
appleScriptObject = nil;
NSString *charToReturn = [objectReturned stringValue];
if (charToReturn == nil ){
charToReturn = [NSString stringWithString:@"error"];
}
[charToReturn retain];
[thePool drain];
[charToReturn autorelease];
return charToReturn;
}
The problem is, this is leaking tons of memory. I admit fully that I do not completely understand memory allocations in Cocoa, so I was hoping someone might be able to explain to me why this is so leaky even with the autorelease pool.
Any help is greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
永远不要这样做。如果您错误地使用此方法(不太可能)或给它一个错误的脚本(很有可能)或某些内容在其他应用程序端不起作用(很可能),您将无法找出问题所在。让框架告诉你出了什么问题。
另外,
nil
在这里是错误的常量。nil
是对象指针类型的空指针;Nil
用于Class
值,NULL
用于其他所有值。这已经是一个字符串了。您不需要用它创建另一个字符串。
您是否已通过 Instruments 验证您实际上正在泄漏源自此方法的 AppleScript 相关对象?
我在方法中看不到任何看起来错误的地方。池应该是不必要的,但您对它的使用是有效且正确的。
您可以尝试使用 OSAKit,特别是它的 OSAScript 类。它没有记录,但两个类的接口几乎相同。
Don't ever do this. If you use this method wrong (unlikely) or give it a bad script (quite possible) or something doesn't work on the other application's end (very likely), you will be unable to find out what the problem is. Let the framework tell you what's wrong.
Plus,
nil
is the wrong constant here.nil
is the null pointer for object pointer types;Nil
is forClass
values, andNULL
is for everything else.This is already a string. You don't need to create another string with it.
Have you verified with Instruments that you are actually leaking AppleScript-related objects that originate in this method?
I can't see anything in the method that looks wrong. The pool should be unnecessary, but your use of it is valid and correct.
You might try using the OSAKit, particularly its OSAScript class, instead. It's not documented, but the two classes' interfaces are pretty much the same.