Last active
August 29, 2015 13:56
-
-
Save raimon49/9031914 to your computer and use it in GitHub Desktop.
Effective Objective-C 2.0メモ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 読み出しを通常のブロック, 書き込みをバリアブロックとして並列キューで処理 | |
_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