特别是,这种代码总是按预期工作(其中MyResourceGuard是一个对象,它在其init方法中锁定独占资源并释放其dealloc方法中的锁):
NSLog(@"About to capture some exclusive resource.");
{
MyResourceGuard* guard = [MyResourceGuard new];
// Do something with the exclusive resource here.
}
// guard is out of scope, therefore its dealloc should have
// been called right away and the resource should already
// be free again at this point.
Run Code Online (Sandbox Code Playgroud)
我已阅读书籍和博客,与例如Java垃圾收集相反,ARC一旦引用计数减少到零就会销毁对象(而不是在它自己方便的某个时间),但我没有在任何官方读过这个Apple提供的文档.如果这是真的,为什么我们需要在ARC中引入新的@autoreleasepool关键字?
从调试开始,我总是看到对象dealloc'ed立即,除非在try-catch-block中引发异常,在这种情况下dealloc实际上从未被调用(是Mac bug,或者只是这些可怕的目标之一) C古怪?).
我们有一个NSTableRowView的子类,它覆盖了drawSelectionInRect :(由drawRect :)内部调用.这个方法需要访问NSManagedObjectContext,所以作为一个完整性检查,我们在那里断言我们在主线程中.现在事实证明Apple有时会从非主线程调用drawRect(下面的示例堆栈跟踪).这是否意味着它甚至可以从两个不同的线程同时执行此操作?也就是说,当我们覆盖drawRect时,我们必须自己处理线程安全:并使用数据模型?
ERROR: Assertion failed: [NSThread isMainThread]: (ZS_AppDelegate.m:1287)
(
0 tomedo_kunden 0x00000001008af46a -[ZS_AppDelegate loggedInUser] + 554
1 tomedo_kunden 0x00000001016feca7 +[Nutzer loggedInUser] + 71
2 tomedo_kunden 0x0000000100f33397 +[ZSUserDefaults(MacOS) colorFromPreferences:] + 167
3 tomedo_kunden 0x00000001003d8265 -[Besuch(BesuchCategory) baseTextColor] + 101
4 tomedo_kunden 0x000000010071f846 -[ZSTableRowView drawSelectionInRect:] + 806
5 AppKit 0x00007fffd189d26c -[NSTableRowView drawRect:] + 242
6 AppKit 0x00007fffd184eba3 -[NSView(NSInternal) _recursive:displayRectIgnoringOpacity:inGraphicsContext:CGContext:topView:shouldChangeFontReferenceColor:] + 1318
7 AppKit 0x00007fffd184f053 -[NSView(NSInternal) _recursive:displayRectIgnoringOpacity:inGraphicsContext:CGContext:topView:shouldChangeFontReferenceColor:] + 2518
8 AppKit 0x00007fffd184e548 __46-[NSView(NSLayerKitGlue) drawLayer:inContext:]_block_invoke + 267
9 AppKit 0x00007fffd184e071 -[NSView(NSLayerKitGlue) _drawViewBackingLayer:inContext:drawingHandler:] + 1589 …