gpt4 book ai didi

c++ - 使用#define 替换代码

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:48:50 26 4
gpt4 key购买 nike

我的 iOS 应用程序中有一堆代码,我必须在每个 View 中使用它 - 不能在函数/方法中使用它 - 所以我想知道是否有任何方法可以使用 #define 并使用它需要的标识符。以下是示例代码。

我想用#deinfe identifer 替换的代码

[[NSNotificationCenter defaultCenter] addObserver:self 
selector:@selector(_gotECSlidingViewAnchorRightOrRightrNotification)
name:ECSlidingViewTopDidAnchorLeft
object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(_gotECSlidingViewAnchorRightOrRightrNotification)
name:ECSlidingViewTopDidAnchorRight
object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(_gotECSlidingViewTopDidResetNotification)
name:ECSlidingViewTopDidReset
object:nil];

所以我想知道如何#define 它并在 ViewDidLoad 方法中使用它?

最佳答案

这不会直接回答您的问题,但作为一个处理过预处理器许多令人头疼的问题的老 C++ 程序员,我建议不要为此使用 #define。

几个选项...

  1. 使用您的两个选择器定义一个基类(派生自 UIViewController)。选择器可以在您的派生类中被覆盖。

    @interface YourBaseCass : UIViewController

    • (void)viewDidLoad;//在这里放置你的添加观察者逻辑
    • (无效)_gotECSlidingViewAnchorRightOrRightrNotification;
    • (void)_gotECSlidingViewTopDidResetNotification;

    @结束

    @implementation YourBaseCass

    - (void)viewDidLoad //make sure you call me from the derived class
    {
    [super viewDidLoad]
    [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(_gotECSlidingViewAnchorRightOrRightrNotification)
    name:ECSlidingViewTopDidAnchorLeft
    object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(_gotECSlidingViewAnchorRightOrRightrNotification)
    name:ECSlidingViewTopDidAnchorRight
    object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(_gotECSlidingViewTopDidResetNotification)
    name:ECSlidingViewTopDidReset
    object:nil];
    }

    @end

  2. 将您的功能放在一个全局静态方法中(如果您不喜欢子类化)。这将更容易调试。

    • (void)addObserversForObject:(id)object{ [[NSNotificationCenter defaultCenter] addObserver:object 选择器:@选择器(_gotECSlidingViewAnchorRightOrRightrNotification) 名称:ECSlidingViewTopDidAnchorLeft 对象:无];

      [[NSNotificationCenter defaultCenter] addObserver:object
      selector:@selector(_gotECSlidingViewAnchorRightOrRightrNotification)
      name:ECSlidingViewTopDidAnchorRight
      object:nil];

      [[NSNotificationCenter defaultCenter] addObserver:object
      selector:@selector(_gotECSlidingViewTopDidResetNotification)
      name:ECSlidingViewTopDidReset
      object:nil];

关于c++ - 使用#define 替换代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15355385/

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