I am having a slight confusion with the self pointer. I understand that if I want to use self in objective C, I need to pass it as a parameter e.g.
我对self指针有点困惑。我理解如果我想在objective C中使用self,我需要将它作为参数传递给。
someFunction(id self)
{
}
What I'm slightly confused about however is that if I want to use self's member variables, I get the following error
然而,我有点困惑的是,如果我想使用self的成员变量,我会得到以下错误
Property 'browser' not found on object of type '__strong id'.
属性“浏览器”在“__strong id”类型的对象上没有找到。
I've defined browser in my header file as:
我在我的头文件中定义了浏览器为:
@property webBrowser* browser;
I am then trying to call a function of my webBrowser class in my c++ function:
然后我尝试调用我的c++函数中的webBrowser类的一个函数:
[self.browser StartSearch:self];
The error occurs in the line above. The function is definitely called correctly if I instead pass self's member variable as a parameter instead. This feels rather hacky though.
错误发生在上面这一行。如果我将self的成员变量作为参数传递,那么函数肯定会被正确调用。不过,这感觉相当陈腐。
Any explanation as to why it doesn't work and what an alternative would be, would be great.
任何关于它为什么不起作用的解释和替代方案,都是很好的。
2 个解决方案
#1
3
In order to use property syntax with dot, you need to provide the compiler with the exact type, for example by casting the id
pointer to the type of your class. If you do not want to use the exact type or cast, use method call syntax:
为了使用带有点的属性语法,您需要向编译器提供精确的类型,例如将id指针转换为类的类型。如果您不想使用确切的类型或类型转换,请使用方法调用语法:
[[self browser] StartSearch:self];
#2
2
You can simply specify the parameter type rather than using a generic id
:
您可以简单地指定参数类型,而不用通用id:
void someFunction(MONObject * self) {
[self.browser StartSearch:self];
}
Or if you feel you really, really, really need the type erasure (e.g. for compilation firewall), you might consider rewriting it this way:
或者,如果你真的、真的、真的需要类型擦除(比如编译防火墙),你可以考虑这样重写:
// Some.mm
void someFunction(id self) {
MONObject * object(self);
[object.browser StartSearch:self];
}
#1
3
In order to use property syntax with dot, you need to provide the compiler with the exact type, for example by casting the id
pointer to the type of your class. If you do not want to use the exact type or cast, use method call syntax:
为了使用带有点的属性语法,您需要向编译器提供精确的类型,例如将id指针转换为类的类型。如果您不想使用确切的类型或类型转换,请使用方法调用语法:
[[self browser] StartSearch:self];
#2
2
You can simply specify the parameter type rather than using a generic id
:
您可以简单地指定参数类型,而不用通用id:
void someFunction(MONObject * self) {
[self.browser StartSearch:self];
}
Or if you feel you really, really, really need the type erasure (e.g. for compilation firewall), you might consider rewriting it this way:
或者,如果你真的、真的、真的需要类型擦除(比如编译防火墙),你可以考虑这样重写:
// Some.mm
void someFunction(id self) {
MONObject * object(self);
[object.browser StartSearch:self];
}