来自Symbian的背景,我有点担心Cocoa中似乎缺乏错误处理.Cocoa有很多方法,据我所知,它没有错误报告,但可能会失败.
例如,为什么NSMutableString appendString有一个void返回类型,并且不抛出异常(至少文档没有提到任何)?当然,如果我追加一个足够长的字符串,理论上我可能会耗尽内存.在追加验证附件是否有效之前和之后检查NSMutableString的长度是不是很偏执?
我的测试是在Mac OS X上,我想你在谈论iPhone平台.
问题是我没有看到如何从appendString方法返回错误会有所帮助,因为平台处于这样一种状态,即它无法满足您的进程的malloc请求.
要解决这个问题,您可以使用自己的地址空间,并将此进程管理的内存用作字符串的存储空间.我认为Carbon的CFString(免费桥接到NSString)允许你使用自己的内存分配器.
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [NSAutoreleasePool new];
NSMutableString * m = [NSMutableString stringWithCapacity:100000];
int i;
for(i=0;i<1000000;i++)
[m appendString:@"ABCDE..."]; //1400 characters long
[pool release];
}
cd:tmp diciu$ ./a.out
a.out(2216) malloc: *** mmap(size=1220067328) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
[..]
2009-08-13 16:45:44.163 a.out[2216:10b] *** Terminating app due to uncaught exception 'NSMallocException', reason: 'Out of memory. We suggest restarting the application. If you have an unsaved document, create a backup copy in Finder, then try to save.'
2009-08-13 16:45:44.165 a.out[2216:10b] Stack: (
2494541803,
2485014075,
2435399864,
2494157025,
2494172776,
2434276628
)
Trace/BPT trap
Run Code Online (Sandbox Code Playgroud)