强制类发布特定的NSNotification? [英] Enforcing that a class posts a particular NSNotification?

查看:128
本文介绍了强制类发布特定的NSNotification?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there any way to ensure that a class posts a particular NSNotification?

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

(I have a set of classes, and I would like to enforce at compile-time (if possible) that the class posts a required NSNotification).

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

Alternatively, if that is not possible, is there any workaround?

推荐答案

从根本上不可能在编译时预测在运行时会发生什么。你可以得到的最接近的是静态分析,但即使不能预测在你自己的代码之外发生的任何事情,如在Foundation内。

It's fundamentally impossible to predict at compile time what will happen at run time. The closest you can get is static analysis, but even that can't predict anything that happens outside of your own code, such as inside Foundation.

使用单元测试执行此操作,因为测试运行程序实际上运行的是测试下的代码。

You can, however, do this with unit tests, since the test runner actually runs the code under test.

您需要创建测试包目标(如果尚未创建的话)。您的目标将使用SenTestingKit运行您创建的测试。 (在iPhone上,您还需要Google Toolbox for,uh,Mac。他们有一个使用GTM for iPhone测试的实用教程

You'll need to create a test bundle target, if you haven't already. Your target will use SenTestingKit to run your tests, which you create. (On the iPhone, you'll also need Google Toolbox for, uh, Mac. They have a handy tutorial on using GTM for iPhone tests.)

你将创建一个SenTestCase子类来测试你的真实对象通知。它看起来像这样:

You'll create a SenTestCase subclass to test whether your real object posts a notification. It'll look something like this:

@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,您需要测试的每个通知的变量和一个通知处理程序方法,以及您要测试通知的每个方法的一个测试方法。 ,您必须用上面的SenTestCase代替GTMSenTestCase。

Also, if using GTM, you must substitute GTMSenTestCase for SenTestCase above.

这篇关于强制类发布特定的NSNotification?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆