开发者

thread safe in iOS development

From wikipedia explanation about thread-safety,thread safe codes can be run in multithreads.

For iOS 3.x, UIKit is not thread safety, since 4.0, UIKIt is thread safet开发者_StackOverflow社区y.

In our implementations, we can use synchronized to build thread safety codes. My questions about thread safety are:

1). How to detect thread safety coding issue with instruments tools or other ways ? 2). Any good practices to write thread safety codes for iOS development ?


since 4.0, UIKIt is thread safety.

Basically, UIKit is not thread-safe. Only drawing to a graphics context in UIKit is thread-safe since 4.0.

1) Hmm, I also want to know about that :-)

2) How about Concurrency Programming Guide?


To make a non thread-safe object thread safe, consider using a proxy (see the code below). I use it for example for NSDateFormatter, which is not a thread safe class, when parsing data in a background thread.

/**
 @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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜