1

我试图为我用 xcode 编写的计时器程序设置一个数组。这些值以秒为单位,我想要的是在界面构建器中有一个按钮,它以该秒数启动计时器。这是我试图声明以在 .h 头文件中提供时间的结构。它只是一个包含 2 个数组的数组,我可以用 @collegeTimes.constructive 或类似的东西调用它。

提前致谢!

- (NSDictionary *)debateTimes;
 id debateTimes = [[NSDictionary alloc] initWithObjectsAndKeys:
 [NSDictionary dictionaryWithObjectsAndKeys:
   @"540", @"constructive",
   @"360", @"rebuttal",
   @"180", @"cx",
   @"600", @"prep",
     nil], @"collegeTimes",
 [NSDictionary dictionaryWithObjectsAndKeys:
   @"480", @"constructive",
   @"300", @"rebuttal",
   @"180", @"cx",
   @"480", @"prep",
     nil], @"hsTimes",
                   nil]; \\error is called here.
4

2 回答 2

4

这是我试图声明以在 .h 头文件中提供时间的结构

这就是问题。您不能在函数之外创建常量NSDictionary对象(或大多数其他对象)。NS做你想做的一种方法如下:

某事.h

@interface SomeThing : NSObject
{
    ...
}
+ (NSDictionary *)debateTimes;
@end

某事.m

static NSDictionary * staticDebateTimes = nil;
@implementation SomeThing
...
+ (NSDictionary *)debateTimes
{
    if (staticDebateTimes == nil)
    {
        staticDebateTimes = [[NSDictionary alloc] initWithObjectsAndKeys:
          [NSDictionary dictionaryWithObjects:...
    }
    return staticDebateTimes;
}
@end

该代码现在将在外部使用,如下所示:

NSDictionary * debateTimes = [SomeThing debateTimes];
于 2011-01-13T21:38:35.767 回答
2

您不能将objective-c 对象分配给函数外部的变量。当一个变量在函数外部赋值时,它的值就变成了可执行文件的一部分。由于指向对象的指针的值直到运行时才知道,所以在创建对象之前不能分配对象。(常量 NSString 是一个例外,因为它们也是可执行文件的一部分)

存储这种结构的最佳方法是使用 c 结构数组。

typedef struct {
    char *name;

    NSTimeInterval constructive;
    NSTimeInterval rebuttal;
    NSTimeInterval cx;
    NSTimeInterval prep;
} DebateTime;
DebateTime[2] = {{"collegeTimes", 540, 360, 180, 600},
                 {"hsTimes", 480, 300, 180, 480}};

如果您愿意,您还可以将名称和时间间隔更改为常量字符串。

于 2011-01-13T21:39:46.337 回答