Skip to content

Instantly share code, notes, and snippets.

@raimon49

raimon49/gist:9031914

Last active Aug 29, 2015
Embed
What would you like to do?
Effective Objective-C 2.0メモ
// 読み出しを通常のブロック, 書き込みをバリアブロックとして並列キューで処理
_syncQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
- (NSString *)someString
{
__block NSString *localSomeString;
dispatch__sync(_syncQueue, ^{
localSomeString = _someString;
});
return localSomeString;
}
- (void)setSomeString:(NSString *)someString
{
dispatch_barrier_async(_syncQueue, ^{
_someString = someString;
});
}
// コンパイル時に代入できないstatic定数はinitializeをオーバーライドして初めてクラスが使われるタイミングで設定
static const int kInterval = 10;
static NSMutableArray *kSomeObjects;
@implementation EOCClass
+ (void)initialize
{
if (self == [EOCClass class]) {
kSomeObjects = [NSMutableArray new];
}
}
@end
// NSTimerの循環参照を防ぐためにブロックを受け取るAPIをカテゴリで定義
@interface NSTimer (EOCBlocksSupport)
+ (void)eoc_scheduledTimerWithTimeInterval:(NSTimeInterval)interval
block:(void(^)())block
repeats:(BOOL)repeats;
@end
@implementation NSTimer (EOCBlocksSupport)
+ (void)eoc_scheduledTimerWithTimeInterval:(NSTimeInterval)interval
block:(void(^)())block
repeats:(BOOL)repeats
{
return [self scheduledTimerWithTimeInterval:interval
target:self
selector:@selector(eoc_blockInvoke:)
userInfo:[block copy]
repeats:repeats];
}
+ (void)eoc_blockInvoke:(NSTimer*)timer
{
void (^block)() = timer.userInfo;
if (block) {
block();
}
}
@end
// selfは弱参照に代入してからブロックの中で使う
- (void)startPolling
{
__weak EOCClass *weakSelf = self;
_pollTimer =
[NSTimer eoc_scheduledTimerWithTimeInterval:5.0
block:^{
__strong EOCClass *strongSelf = weakSelf;
[strongSelf p_doPoll];
}
repeats:YES];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment