【问题标题】:Declaring arrays statically in Constants file在常量文件中静态声明数组
【发布时间】:2014-01-24 03:29:22
【问题描述】:

我在一个 Constants.m 文件中声明了一些静态数组,例如我的 tableView 的 numberOfRowsInSection 计数:

+ (NSArray *)configSectionCount
{
    static NSArray *_configSectionCount = nil;
    @synchronized(_configSectionCount) {
        if(_configSectionCount == nil) {
            _configSectionCount = [NSArray arrayWithObjects:[NSNumber numberWithInt:2], [NSNumber numberWithInt:2], [NSNumber numberWithInt:4], [NSNumber numberWithInt:3], [NSNumber numberWithInt:0], nil];
        }
        return _configSectionCount;
    }
}

这是最好的方法吗?是否有必要像这样声明它们?

【问题讨论】:

  • 查看dispatch_once 而不是@synchronized

标签: objective-c static constants


【解决方案1】:

我做的是:

// main.m
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "Constants.h"
int main(int argc, char * argv[])
{
    @autoreleasepool {
        [Constants class];
        return UIApplicationMain(argc, argv, nil, 
                   NSStringFromClass([AppDelegate class]));
    }
}

// Constants.h
extern NSArray* configSectionCount;
#import <Foundation/Foundation.h>
@interface Constants : NSObject
@end

// Constants.m
#import "Constants.h"
@implementation Constants
NSArray* configSectionCount;
+(void)initialize {
    configSectionCount = @[@2, @2, @4, @3, @0];
}
@end

现在任何导入Constants.h.m 文件都可以访问configSectionCount。为了更容易,我的 .pch 文件包含以下内容:

// the .pch file
#import "Constants.h"

完成。现在configSectionCount 绝对是全球性的。 (你真的应该给这些全局变量一个特殊格式的名字,比如gCONFIG_SECTION_COUNT。否则你明天就不会明白它来自哪里。)

【讨论】:

  • 非常感谢 - 看起来很干净
  • 没问题。你明白在 main.m 文件中说[Constants class] 的目的吧?它是为了使 Constants 类出现并运行它的initialize任何其他类(例如 AppDelegate)被实例化,从而初始化我们的全局变量。如果你不喜欢这种方法,你可以在 AppDelegate 本身中做同样的事情,如果这足够早的话。
  • 是的,我想我更喜欢 AppDelegate,因为这很适合我的需要。刚刚使用您的方法重构了我的应用程序,我的代码更易于管理。我也不知道arrayWithObjectsnumberWithInt 语法的简写——所以也更新了所有这些,它更漂亮!
  • 如果您要求 Xcode 将所有符号更新为“现代 Objective-C”:编辑 > 重构 > 转换为现代 Objective-C 语法。
猜你喜欢
  • 1970-01-01
  • 2015-12-15
  • 1970-01-01
  • 1970-01-01
  • 2016-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多