Objective-C - if 内的不可变声明 - 范围和内存管理?
在Apple文档中,声明NSDate对象是不可变的,我认为这意味着一旦用值初始化它们,它们就不能/不应该被更改。
但是,在下面的代码中,我需要 NSDate 作为两个可能值之一,所以我自然可以使用:
for (class* object in array) {
if (i == 0) {
NSDate* fromDate = //...a date
} else {
NSDate* fromDate = //...a different date
}
//Use fromDate
i++
}
据我所知,这是无效的,因为在 if 块之外使用 fromDate 超出了范围。
解决方案通常是:
for (class* object in array) {
NSDate* fromDate = [[NSDate alloc] init];
if (i == 0) {
fromDate = //...a date
} else {
fromDate = //...a different date
}
//Use then release fromDate
i++
}
但是,根据 Apple 文档,当 NSDate 收到“init”时,它会使用今天的日期进行初始化,并且由于它是不可变的,因此我无法重新分配它。
这里正确的做法是什么?是否只是将我的所有代码复制到 if 块中两次?或者我误解了“不可变”这个词?或者也许我需要在第一个示例中的赋值之后保留?
谢谢
In the Apple Documentation, it is stated that NSDate objects are immutable which I presume means that once they are initialised with a value, they cannot/shouldn't be changed.
However, in the following code I need an NSDate to be one of two possible values so naturally i might use:
for (class* object in array) {
if (i == 0) {
NSDate* fromDate = //...a date
} else {
NSDate* fromDate = //...a different date
}
//Use fromDate
i++
}
As far as I'm aware, this is not valid because using fromDate outside the if block is outside of scope.
The solution would normally be:
for (class* object in array) {
NSDate* fromDate = [[NSDate alloc] init];
if (i == 0) {
fromDate = //...a date
} else {
fromDate = //...a different date
}
//Use then release fromDate
i++
}
However, according to the Apple Docs, when an NSDate receives 'init' it's initialised with todays date and since it's immutable, I can't reassign it.
What's the correct thing to do here? Is it simply to copy all of my code into the if blocks twice? Or have I misunderstood the term immutable? Or perhaps I need a retain after the assignment in the first example?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的问题还揭示了对指针如何工作的根本误解。是的,文档说
NSDate
对象是不可变的。但fromDate
不是NSDate
。它是一个NSDate*
。换句话说,它只是一个指向实际NSDate
对象所在位置的转发地址。指针本身是可变的(除非将其声明为 const),并且您可以随意更改指针的值,只要您愿意。然而,指针指向的东西(实际的 NSDate )是正确的不可变的。Your question also reveals a fundamental misunderstanding of how pointers work. Yes, the documentation says that
NSDate
objects are immutable. ButfromDate
is not anNSDate
. It is anNSDate*
. In other words, it is simply a forwarding address that points to where the actualNSDate
object lives. The pointer itself is mutable (unless it's declared asconst
), and you can feel free to change the pointer's value as much as you like. However, the thing that the pointer points to (the actualNSDate
) is correctly immutable.声明变量时不必将其分配给任何内容。
You don't have to assign it to anything when you declare the variable.