Skip to content

Instantly share code, notes, and snippets.

@KanybekMomukeyev
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 KanybekMomukeyev/9320939 to your computer and use it in GitHub Desktop.
Save KanybekMomukeyev/9320939 to your computer and use it in GitHub Desktop.
Answers to questions.
//(1) Ответы на первый вопрос.
@interface Foo : SomeObject
{
NSString *_bar;
}
@property (retain) NSString *bar;
+ (id)foo;
@end
@implementation Foo
@synthesize bar = _bar;
- (NSString *)bar
{
return _bar;
}
- (void)setBar:(NSString *)bar
{
if (bar != _bar) {
[bar retain];
[_bar release];
_bar = bar;
}
}
// Update, тут все верно
+ (id)foo
{
Foo *foo = [Foo alloc];
[foo init];
return [foo autorelease];
}
- (void)dealloc
{
[_bar release]; // add release
self.bar = nil;
[super dealloc];
}
//(2) Ответы на 2-ой вопрос.
- (void)generateBlocks
{
int i = 0;
dispatch_block_t blockA = [^{ // добавили copy
NSLog(@"i == %d", ++i);
} copy];
__weak Test *weakSelf = self; // добавили __weak
dispatch_block_t blockB = [^{
NSLog(@"self.i == %d", weakSelf.i);
} copy];
dispatch_block_t blockC = [^{
NSLog(@"Hello from blockC!");
} copy];
self.blocks = @[blockA, blockB, blockC];
}
- (void)dealloc
{
self.blocks = nil;
[super dealloc];
}
// Ответ на 3 вопрос.
// Я не поклонник NSThread и performSelectorInBackgroung.
// поэтому попробую предложить вариант решений с GCD.
// код взял из BlocksKit.
#import "NSTimer+BlocksKit.h"
@interface NSTimer (BlocksKitPrivate)
+ (void)bk_executeBlockFromTimer:(NSTimer *)aTimer;
@end
@implementation NSTimer (BlocksKit)
+ (id)scheduledTimerWithTimeInterval:(NSTimeInterval)inTimeInterval block:(BKTimerBlock)block repeats:(BOOL)inRepeats
{
NSParameterAssert(block);
return [self scheduledTimerWithTimeInterval: inTimeInterval
target: self
selector: @selector(bk_executeBlockFromTimer:)
userInfo: [block copy]
repeats: inRepeats];
}
+ (void)bk_executeBlockFromTimer:(NSTimer *)aTimer
{
BKTimerBlock block = [aTimer userInfo];
if (block) block(aTimer);
}
@end
........
- (void)start
{
self.timer = [NSTimer scheduledTimerWithTimeInterval:10.0f
block:^(NSTimer *aTimer){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"User info: %f", [aTimer timeInterval]);
});
}
repeats:YES];
}
........
@KanybekMomukeyev
Copy link
Author

Comments are welcome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment