【问题标题】:Override a static constant int in .h file in Objective-C?在Objective-C中覆盖.h文件中的静态常量int?
【发布时间】:2020-12-13 17:15:00
【问题描述】:

我正在尝试在 OC 中构建一个应用程序,并在 .h 文件中有一个常量,就像这样定义菜单上应该有多少列:

// cellManager.h
static int const cellNumberPerRow = 4;

现在在我的视图管理器文件(.m)中,当字体大小发生变化时,我需要将列数更改为 3。到目前为止,我已经尝试过:

// menuManagerView.m
if ([self isBigFontSize]) {
     // ....
     cellNumberPerRow = 3;
     // ...

但这给了我一个错误Cannot assign to variable 'cellNumberPerRow' with const-qualified type 'const int';当我尝试像这样添加标识符时:

static int const cellNumberPerRow = 3;

有警告Unused variable 'cellNumberPerRow',列号保持4;

我觉得应该有一种优雅的方式来做到这一点,但在任何地方都找不到。我真的是 iOS 开发新手,所以非常感谢任何人的意见,谢谢!

更新

我定义了一个新的整数变量,将 const 变量的值赋给它,并用 .m 文件中的新变量替换了所有旧的 cellNumberPerRoe。现在它起作用了。但我想知道是否有更好的方法来做到这一点?

static int newCellNumberPerRow = cellNumberPerRow;

【问题讨论】:

    标签: ios objective-c iphone user-interface view


    【解决方案1】:

    如果您想在某些情况下更改常量的值,则意味着它不再是常量。您可以使用指针绕过const 编译器检查,但这会适得其反。完全从定义中删除 const 会容易得多。

    作为 替代方法,我建议的是文件管理器类中的计算属性,定义如下:

    typedef NS_ENUM(int, CellNumberPerRow) {
        defaultCellNumberPerRow = 4,
        smallerCellNumberPerRow = 3,
    };
    
    @interface YourManager: NSObject
    @property(readonly,nonatomic) int currentCellNumberPerRow;
    @end
    
    @implementation DocumentItem
    -(int)currentCellNumberPerRow {
         if ([self isBigFontSize]) {
            return smallerCellNumberPerRow;
         }
         return defaultCellNumberPerRow;
    }
    @end
    

    现在要获得每行适当的单元格编号,您可以改用 currentCellNumberPerRow 属性。

    也许将currentCellNumberPerRow 设为类属性@property(class,...) 而不是实例属性也会变得方便。

    【讨论】:

      猜你喜欢
      • 2012-07-14
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      • 1970-01-01
      相关资源
      最近更新 更多