Objective c 在传递给c函数的块中使用self而不使用上下文参数
当我们使用GCD的Objective c 在传递给c函数的块中使用self而不使用上下文参数,objective-c,c,block,self,dylib,Objective C,C,Block,Self,Dylib,当我们使用GCD的dispatch\u async功能时,我们可以执行以下操作: - (void)aMethod { dispatch_async(dispatch_get_concurrent_queue(0, 0), ^{ [self anOtherMethod]; self.aProperty = @"Hello"; }); - (void)aMethod { MyCFunctionFromDylib(NULL, ^(void *context){
dispatch\u async
功能时,我们可以执行以下操作:
- (void)aMethod {
dispatch_async(dispatch_get_concurrent_queue(0, 0), ^{
[self anOtherMethod];
self.aProperty = @"Hello";
});
- (void)aMethod {
MyCFunctionFromDylib(NULL, ^(void *context){
// the first argument is the context, NULL here
[self anOtherMethod];
});
}
- (void)anOtherMethod {
[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationName" object:self];
}
我们可以在这里看到,我们可以在传递给C函数的块中使用self
和属性,而无需任何上下文参数
我在C和CoreFoundation中创建了一个动态库(链接到CoreFoundation和IOKit框架),我使用它如下:
- (void)aMethod {
dispatch_async(dispatch_get_concurrent_queue(0, 0), ^{
[self anOtherMethod];
self.aProperty = @"Hello";
});
- (void)aMethod {
MyCFunctionFromDylib(NULL, ^(void *context){
// the first argument is the context, NULL here
[self anOtherMethod];
});
}
- (void)anOtherMethod {
[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationName" object:self];
}
该块由dispatch\u async
执行:
void MyCFuntionFromDylib(void *context, void (^the_block)(void* context) ) {
dispatch_async(dispatch_get_concurrent_queue(0,0), ^{
the_block(context);
});
在这里,它不起作用。我的应用程序因一些不同的错误而崩溃。当[self-anOtherMethod]时,cfbasichfindbucket
中有时会出现奇怪的错误代码>被执行。有时,它在\u dispatch\u client\u callout
(libdispatch的功能部分,由GCD使用)中崩溃,有时我会收到一个选择器未识别的错误
如果我将self
传递给context
参数,它工作正常。但是,除了使用如上所示的self
insidedispatch\u async
之外,我还能做些什么来获得相同的行为呢?您是使用ARC(自动引用计数),还是手动保留和释放对象?“如果我将self传递给上下文参数,它工作正常。”这样就不太安全了,因为没有保留self
。如果MyCFunctionFromDylib
不是来自动态库,它会崩溃吗?