0

有没有办法确保一个类发布一个特定的 NSNotification?

(我有一组类,我想在编译时(如果可能)强制该类发布所需的 NSNotification)。

或者,如果这不可能,是否有任何解决方法?

4

1 回答 1

3

在编译时预测运行时会发生什么基本上是不可能的。您可以获得的最接近的是静态分析,但即使这样也无法预测在您自己的代码之外发生的任何事情,例如在 Foundation 内部。

但是,您可以使用单元测试来执行此操作,因为测试运行程序实际上会运行被测代码。

如果您还没有创建测试包目标,则需要创建该目标。您的目标将使用 SenTestingKit 运行您创建的测试。(在 iPhone 上,你还需要谷歌工具箱,呃,Mac。他们有一个关于使用 GTM 进行 iPhone 测试的方便教程。)

您将创建一个 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。

于 2009-06-30T07:52:36.910 回答