仅当我使用中间变量时才有效
我试图将 UILabel 的文本设置为等于 NSDateComponents 中表示的星期几的名称。我使用以下代码:
NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease];
dateComponents.weekday = 1; //Sunday
NSString * const weekdayNames[8] = {@"Array starts at 1", @"Sunday", @"Monday", @"Tuesday", @"Wednesday", @"Thursday", @"Friday", @"Saturday"};
UILabel *myLabel = [[[UILabel alloc] init] autorelease];
myLabel.text = weekdayNames[dateComponents.weekday]; //compiler error: Assignment of read-only variable 'prop.49'
我可以通过以下三种方式中的任何一种使代码工作:
- 使 weekdayNames 不是 const
- 将 dateComponents.weekday 分配给中间 int 变量,然后将其用作数组索引
- 将 weekday[dateComponents.weekday] 分配给中间变量NSString * 调用 setText 之前的变量:
但我想知道为什么我的代码(如最初编写的那样)失败了。
I am trying to set the text of a UILabel to be equal to the name of the day of the week represented in an NSDateComponents. I am using the following code:
NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease];
dateComponents.weekday = 1; //Sunday
NSString * const weekdayNames[8] = {@"Array starts at 1", @"Sunday", @"Monday", @"Tuesday", @"Wednesday", @"Thursday", @"Friday", @"Saturday"};
UILabel *myLabel = [[[UILabel alloc] init] autorelease];
myLabel.text = weekdayNames[dateComponents.weekday]; //compiler error: Assignment of read-only variable 'prop.49'
I can make the code work in any of three ways:
- Make weekdayNames not be const
- Assign dateComponents.weekday to an intermediate int variable before using it as an array index
- Assign weekday[dateComponents.weekday] to an intermediate NSString * variable before calling setText:
But I want to know why my code, as originally written, fails.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有正确初始化 NSDateComponents,因此工作日不会返回您期望的值。请参阅文档。
现在您将使用当前日期对其进行初始化:
稍后编辑:初始化是问题的一部分,以修复编译器错误更改:
为
(指向常量 NSString 的指针)。
但是,当您这样做时,您将收到警告“传递‘setText:’的参数 1 会丢弃指针目标类型中的限定符”,因为您正在将常量指针传递给需要指针的函数。要修复该警告,您可以将 setText 的参数转换为 (NSString *)。
完全删除 const 限定符可能是有意义的。
NSString 在 Objective-C 中已经是不可变的,因此它们已经是常量。
You are not initializing NSDateComponents properly, thus weekday does not return the value you expect. See the documentation.
This is now you would initialize it using the current date:
Later edit: Initialization is part of the problem, to fix the compiler error change:
to
(pointer to a constant NSString).
However, when you do that you will hit a warning "passing argument 1 of 'setText:' discards qualifiers from pointer target type" because you're passing a constant pointer to a function that expects a pointer. To fix the warning you can cast the argument to setText to (NSString *).
It probably makes sense to remove the const qualifier altogether.
NSStrings are already immutable in Objective-C, so they're already constants.