Cocoa 应用程序中的数组值 - 初始化程序不是常量错误
我试图为我在 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.
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 = [[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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是问题所在。您不能在函数外部创建常量 NSDictionary 对象(或大多数其他 NSDictionary 对象)。做你想做的事情的一种方法如下:
此代码现在可以在外部使用,如下所示:
This is the problem. You can not create constant
NSDictionary
objects (or most otherNS
objects, for that matter) outside of a function. One way to do what wou want would be as follows:This code would now be used externally as follows:
您不能将 Objective-C 对象分配给函数外部的变量。当变量在函数外部分配时,其值将成为可执行文件的一部分。由于指向对象的指针的值直到运行时才知道,因此在创建对象之前无法分配该对象。 (常量 NSString 是一个例外,因为它们也是可执行文件的一部分)
存储此类结构的最佳方法是使用 c 结构数组。
如果您愿意,您还可以将名称和时间间隔更改为常量字符串。
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.
You can also change the name and time intervals to constant strings if you wish.