开发者

Array Values in Cocoa App - Initializer not constant error

开发者 https://www.devze.com 2023-02-04 10:41 出处:网络
Im trying to set an array for a timer program im writing in xcode. the values are in seconds, and what i want is to have a button in the interface builder that starts a timer with that number of secon

Im trying to set an array for a timer program im writing in xcode. the values are in seconds, and what i want is to have a button in the interface builder that starts a timer with that number of seconds. This is the struct im trying to declare to provide the times in a .h header file. its just an array with 2 arrays in it, that i could call with @collegeTimes.constructive or something similar.

Thanks in advance!

- (NSDictionary *)debateTimes;
 id debateTimes = [[NSDicti开发者_Python百科onary 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.


This is the struct im trying to declare to provide the times in a .h header file

This is the problem. You can not create constant NSDictionary objects (or most other NS objects, for that matter) outside of a function. One way to do what wou want would be as follows:

SomeThing.h

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

SomeThing.m

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

This code would now be used externally as follows:

NSDictionary * debateTimes = [SomeThing debateTimes];


You cannot assign an objective-c object to a variable outside of a function. When a variable is assigned outside a function, its value becomes part of the executable. Since the value of the pointer to a object is not known until runtime, you cannot assign the object until it is created. (Constant NSStrings are an exception to this as they are also part of the executable)

The best way to store a structure like this would be to use an array of c structures.

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}};

You can also change the name and time intervals to constant strings if you wish.

0

精彩评论

暂无评论...
验证码 换一张
取 消