2011-04-26 29 views
0

從維基百科解釋關於thread-safety,可以在多線程中運行線程安全代碼。iOS開發中的線程安全

對於iOS 3.x,UIKit不是線程安全的,因爲4.0,UIKIt是線程安全的。

在我們的實現中,我們可以使用synchronized來構建線程安全代碼。我關於線程安全的問題是:

1)。如何使用儀器工具或其他方法檢測線程安全編碼問題? 2)。任何爲iOS開發編寫線程安全代碼的良好實踐?

+0

相關:http://stackoverflow.com/questions/7102797/when-do-i-need-to-worry-about-thread-safety-in-an-ios-application – Thilo 2011-08-18 05:31:31

+0

HTTP:// stackoverflow.com/questions/7702013/drawing-in-a-background-thread-on-ios – DenTheMan 2012-03-06 07:03:06

回答

5

從4.0開始,UIKIt就是線程安全的。

基本上,UIKit不是線程安全的。自從4.0開始,UIKit中繪製到圖形上下文的是線程安全的。

1)嗯,我也想知道這個問題:-)

2)如何Concurrency Programming Guide

1

要使非線程安全的對象線程安全,請考慮使用代理(請參閱下面的代碼)。在後臺線程中解析數據時,我將它用於NSDateFormatter,它不是線程安全類。

/** 
@brief 
Proxy that delegates all messages to the specified object 
*/ 
@interface BMProxy : NSProxy { 
    NSObject *object; 
    BOOL threadSafe; 
} 

@property(atomic, assign) BOOL threadSafe; 

- (id)initWithObject:(NSObject *)theObject; 
- (id)initWithObject:(NSObject *)theObject threadSafe:(BOOL)threadSafe; 

@end 

@implementation BMProxy 

@synthesize threadSafe; 

- (id)initWithObject:(NSObject *)theObject { 
    object = [theObject retain]; 
    return self; 
} 

- (id)initWithObject:(NSObject *)theObject threadSafe:(BOOL)b { 
    if ((self = [self initWithObject:theObject])) { 
     self.threadSafe = b; 
    } 
    return self; 
} 

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { 
    return [object methodSignatureForSelector:aSelector]; 
} 

- (void)forwardInvocation:(NSInvocation *)anInvocation { 
    if (self.threadSafe) { 
     @synchronized(object) { 
      [anInvocation setTarget:object]; 
      [anInvocation invoke]; 
     } 
    } else { 
     [anInvocation setTarget:object]; 
     [anInvocation invoke]; 
    } 
} 

- (BOOL)respondsToSelector:(SEL)aSelector { 
    BOOL responds = [super respondsToSelector:aSelector]; 
    if (!responds) { 
     responds = [object respondsToSelector:aSelector]; 
    } 
    return responds; 
} 

- (void)dealloc { 
    [object release]; 
    [super dealloc]; 
} 

@end 
+0

把它變成'NSObject'的類別。 };) – Barry 2014-07-24 21:14:16