Objective-C:改变“自我”自我内在的价值
我在 NSDate 上有一个类别,我想实现一些函数来操作日期,例如:
NSDate *thedate = [NSDate date];
[thedate setToMidnight];
所以我在 NSDate 中有一个函数,例如:
-(void)setToMidnight {
some code with calendars and comps
self = theNewDate;
}
这在函数内部工作,但在此成员函数之外,日期没有改变。 我理解这种故障,因为我被告知 self 只是在成员函数内创建的局部变量。 那么,我怎样才能做到这一点呢?
当然,我可以写:
thedate = [thedate dateAsMidnightDate]
or thedate = [NSDate dateAtMidnightFromDate:thedate]
但我觉得它在实例类中更有意义,因为我不想更改日期,而只是调整先前创建的日期的一些值。
I have a category on NSDate, and I want to implement some functions to manipulate the date, like :
NSDate *thedate = [NSDate date];
[thedate setToMidnight];
so I have a function in NSDate like :
-(void)setToMidnight {
some code with calendars and comps
self = theNewDate;
}
This works inside the function, but outside this member function, thedate has not changed.
I understand this malfunction because I've been told that self is just a local variable created inside the member function.
So, how can I make this work ?
Of course, I could have written :
thedate = [thedate dateAsMidnightDate]
or thedate = [NSDate dateAtMidnightFromDate:thedate]
but I feel it has more sense inside the instance class, as I don't want to change the date but just adjust some values of the previously created one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能。具体来说:
函数或方法不能修改调用上下文中的局部变量。
NSDate 是不可变的(即 NSDate 一旦创建就不能修改)。
因此,无法编写这样的方法。您可以获得的最接近的是一个包装 NSDate 并将消息转发到该内部 NSDate 对象的类,当您想让日期实例变量代表新日期时,该对象会重新分配日期实例变量。
You can't. Specifically:
A function or method cannot modify local variables in the calling context.
NSDate is not mutable (i.e. you can't modify an NSDate once it's created).
Therefore, no such method can be written. The closest you can get would be a class that wraps an NSDate and forwards messages to that internal NSDate object, which reassigns the date instance variable when you want to make it represent a new date.