Skip to content

Instantly share code, notes, and snippets.

@raimon49
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raimon49/9031914 to your computer and use it in GitHub Desktop.
Save raimon49/9031914 to your computer and use it in GitHub Desktop.
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