有什么方法可以确保类发布特定的 NSNotification?
(我有一组类,我想在编译时(如果可能的话)强制该类发布所需的 NSNotification)。
或者,如果不可能,是否有任何解决方法?
最佳答案
在编译时预测运行时会发生什么基本上是不可能的。您可以获得的最接近的是静态分析,但即使这样也无法预测您自己的代码之外发生的任何事情,例如 Foundation 内部。
但是,您可以通过单元测试来执行此操作,因为测试运行程序实际上运行测试下的代码。
如果您还没有创建测试包目标,则需要创建它。您的目标将使用 SenTestingKit 来运行您创建的测试。 (在 iPhone 上,您还需要适用于 Mac 的 Google 工具箱。它们有 a handy tutorial on using GTM for iPhone tests 。)
您将创建一个 SenTestCase 子类来测试您的真实对象是否发布通知。它看起来像这样:
@interface FrobnitzerNotificationsTest: SenTestCase
{
BOOL frobnitzerDidCalibrate;
}
- (void) frobnitzerDidCalibrate:(NSNotification *)notification;
@end
@implementation FrobnitzerNotificationsTest
- (void) testFrobnitzerCalibratePostsNotification {
Frobnitzer *frobnitzer = …;
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:@selector(frobnitzerDidCalibrate:)
name:FrobnitzerDidCalibrate
object:frobnitzer];
frobnitzerDidCalibrate = NO;
//This should post a notification named FrobnitzerDidCalibrate with the receiver as the object.
[frobnitzer calibrate];
//If it did, our notification handler set frobnitzerDidCalibrate to YES (see below).
[nc removeObserver:self
name:FrobnitzerDidCalibrate
object:frobnitzer];
STAssertTrue(frobnitzerDidCalibrate, @"Frobnitzer did not post a notification when we told it to calibrate");
}
- (void) frobnitzerDidCalibrate:(NSNotification *)notification {
frobnitzerDidCalibrate = YES;
}
@end
对于要测试的每个通知,您都需要一个实例变量和一种通知处理程序方法,并且对于要测试通知的每个方法都需要一个测试方法。
此外,如果使用 GTM,则必须用 GTMSenTestCase 替换上面的 SenTestCase。
关于objective-c - 强制某个类发布特定的 NSNotification?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1062191/