0

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 safety.

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 ?

Forrest
  • 122,703
  • 20
  • 73
  • 107
  • related: http://stackoverflow.com/questions/7102797/when-do-i-need-to-worry-about-thread-safety-in-an-ios-application – Thilo Aug 18 '11 at 05:31
  • http://stackoverflow.com/questions/7702013/drawing-in-a-background-thread-on-ios – DenTheMan Mar 06 '12 at 07:03

2 Answers2

5

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?

Kazuki Sakamoto
  • 13,929
  • 2
  • 34
  • 96
1

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
Werner Altewischer
  • 10,080
  • 4
  • 53
  • 60