gpt4 book ai didi

ios - NSObject 的类别可用于每个 NSObject 子类,即使没有在任何地方导入该类别的 .h 文件

转载 作者:技术小花猫 更新时间:2023-10-29 11:14:34 28 4
gpt4 key购买 nike

背景。

请考虑以下步骤:

1) 在 Xcode 中创建一个新的“单 View 应用程序”。

2)创建类NSObject+Extension.h和.m文件:

// .h
@interface NSObject (Extension)
- (void)someMethod;
@end

// .m
@implementation NSObject (Extension)
- (void)someMethod {
NSLog(@"someMethod was called");
}
@end

3) 确保 NSObject+Extension.m 文件包含在主目标中。

4) 将以下行添加到 AppDelegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[NSString new] performSelector:@selector(someMethod)];

return YES;
}

5) 确保 #import "NSObject+Extension.h line does not exists in anywhere in the app!

6) 运行应用程序。

输出是

2013-08-27 04:12:53.642 Experimental[32263:c07] someMethod was called

问题

  1. 我想知道是否在应用程序中的任何地方都没有此类别的任何#import,怎么可能NSString 仍然有 NSObject+Extension 可用?这种行为让我对我声明的每个 Objective-C 类别都感觉很糟糕,因为我希望我声明的类别仅在它们声明的范围内可用。例如,我希望 NSObject 仅在某些类中通过 Extension 进行扩展,而不是在整个应用程序中进行扩展,否则它的全局空间将被“污染”。

  2. 有没有办法避免这种行为?我确实希望我的类别仅在我明确导入它们时起作用,而不是在我将它们链接到我用来运行的目标时起作用。

最佳答案

I wonder if there is no any #import of this category anywhere in the app, how is it even possible that NSString does still have NSObject+Extension available? This behavior makes me feeling very bad about every Objective-C category I declare because I want the categories I declare to be available only in the scopes they are declared within. For example, I want NSObject to be extended by Extension only in some class but not in the whole app because its globalspace becomes "polluted" otherwise.

Objective-C 对象上没有命名空间。如果您声明一个类有一个方法(无论是通过类别还是在主 @interface 上),那么该类的每个实例都将有该方法。

Objective-C 处理“私有(private)”方法的方式是选择不告诉其他人有问题的方法(这是通过不#import-ing 声明这些方法的文件来实现的)方法)。这与 -Wundeclared-selector(如果您使用编译器不知道的选择器时发出警告)相结合,就相当于您将要获得的保护。

但无论如何,如果您将 .m 文件编译成最终的二进制文件,该方法存在,即使没有其他人“知道”它。

Are there way to avoid this behavior? I do want my categories to work only when I explicitly import them, not just when I have them linked to a target I use to run.

是的,使用 -Wundeclared-selector,Xcode 会警告你。

关于ios - NSObject 的类别可用于每个 NSObject 子类,即使没有在任何地方导入该类别的 .h 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18455541/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com