Category accessing private methods of main class - Objective C

ale*_*ker 3 objective-c private-methods categories

Due to the circumstances of what I'm programming, I need to implement some methods in a class without actually editing the class, so I am using categories.

The trouble is there are methods not included in the interface of the class, but are implemented in the class implementation. I'm assuming this just means they are private methods.

Is it not possible for a category to have access the private methods of its main class? When I try to use one of the private methods in my category I get the error:

"No visible @interface for 'MainClass' declares the selector 'privateMethod'"

这是可以理解的,因为它不在接口中,但是我认为从逻辑上讲,我可以访问实现中的所有内容。

Dar*_*ren 5

您要调用的方法需要在某处声明。您可以使用自己的类别自己声明它们:

@interface MainClass(MyPrivateMethods)
- (CGRect)privateMethod:(NSString*)someParameter;
@end
Run Code Online (Sandbox Code Playgroud)

这将摆脱“ MainClass声明选择器没有可见的@interface”编译器警告,而您只希望它在运行时起作用即可。如果MainClass没有带有这些参数和返回类型的该名称的方法,则它将在运行时失败。

(您也可以使用,performSelector:但根据编译器的设置,仍可能会收到有关无法识别的选择器的警告,并且不适用于所有参数和返回类型)。