有没有办法在延迟后调用带有原始参数的块,比如使用performSelector:withObject:afterDelay:但是使用像int/ double/ 这样的参数float?
__blockObjective-C 中的关键字究竟是什么意思?我知道它允许你修改块内的变量,但我想知道......
我收到了一个错误
变量不可分配(缺少__block类型说明符)
就行了aPerson = participant;.如何确保块可以访问aPerson变量并且aPerson可以返回变量?
Person *aPerson = nil;
[participants enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Person *participant = (Person*)obj;
if ([participant.gender isEqualToString:@"M"]) {
aPerson = participant;
*stop = YES;
}
}];
return aPerson;
Run Code Online (Sandbox Code Playgroud) 是否可以使用标准属性语法将块作为属性?
ARC有什么变化吗?
目标C中的块语法(实际上是C,我推测)是众所周知的不协调.将块作为参数传递看起来与将块声明为ivars不同,后者看起来与typedef块不同.
是否有一个完整的块声明语法列表,我可以随时查看以供快速参考?
我有一个工作的应用程序,我正在努力将其转换为Xcode 4.2中的ARC.其中一个预检警告涉及self强烈捕获导致保留周期的块.我已经制作了一个简单的代码示例来说明问题.我相信我理解这意味着什么,但我不确定实现这种情况的"正确"或推荐方法.
代码示例:
// code sample
self.delegate = aDelegate;
self.dataProcessor = [[MyDataProcessor alloc] init];
self.dataProcessor.progress = ^(CGFloat percentComplete) {
[self.delegate myAPI:self isProcessingWithProgress:percentComplete];
};
self.dataProcessor.completion = ^{
[self.delegate myAPIDidFinish:self];
self.dataProcessor = nil;
};
// start the processor - processing happens asynchronously and the processor is released in the completion block
[self.dataProcessor startProcessing];
Run Code Online (Sandbox Code Playgroud)
问题:我在做什么"错误"和/或如何修改它以符合ARC惯例?
使用GCD时,我们希望等到两个异步块执行完成后再继续执行下一步.最好的方法是什么?
我们尝试了以下方法,但它似乎不起作用:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
// block1
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
// block2
});
// wait until both the block1 and block2 are done before start block3
// how to do that?
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
// block3
});
Run Code Online (Sandbox Code Playgroud) 我担心这个问题非常基本,但我认为这与很多进入数据块的Objective-C程序员有关.
我听到的是,由于块捕获作为const副本在其中引用的局部变量self,因此如果要复制该块,则在块内使用可能会导致保留周期.因此,我们应该使用__block强制块直接处理self而不是复制它.
__block typeof(self) bself = self;
[someObject messageWithBlock:^{ [bself doSomething]; }];
Run Code Online (Sandbox Code Playgroud)
而不仅仅是
[someObject messageWithBlock:^{ [self doSomething]; }];
Run Code Online (Sandbox Code Playgroud)
我想知道的是:如果这是真的,有没有办法可以避免丑陋(除了使用GC)?
除了明显的差异:
enumerateObjectsUsingBlock时,你既需要索引和对象enumerateObjectsUsingBlock当你需要修改局部变量时不要使用被enumerateObjectsUsingBlock普遍认为是好还是坏的时候for (id obj in myArray)也将工作?有哪些优点/缺点(例如性能或多或少)?
是否可以在不使用typedef的情况下在Objective-C中指定方法块参数?它必须像函数指针一样,但是如果不使用中间的typedef,我就无法获得胜利的语法:
typedef BOOL (^PredicateBlock_t)(int);
- (void) myMethodTakingPredicate:(PredicateBlock_t)predicate
Run Code Online (Sandbox Code Playgroud)
只有以上编译,所有这些都失败了:
- (void) myMethodTakingPredicate:( BOOL(^block)(int) ) predicate
- (void) myMethodTakingPredicate:BOOL (^predicate)(int)
Run Code Online (Sandbox Code Playgroud)
我不记得我尝试过的其他组合.