设置方法所需静态对象的正确方法
我正在 NSDate
上创建一个类别,将 NSDate
转换为 NSString
。它使用 NSDateFormatter
来执行此操作。我发现每次分配然后取消分配格式化程序都会在我的应用程序中造成明显的延迟(此类别使用非常频繁),因此我更新了我的“格式”方法,如下所示:
- (NSString *)pretty
{
static NSDateFormatter *formatter = nil;
if (formatter == nil)
{
formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterLongStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
}
return [formatter stringFromDate:self];
}
这是处理静态变量的正确方法吗?可可?这是泄漏吗(alloc
之后没有 dealloc
)?是否存在更好的方法来做这样的事情?谢谢!
I'm creating a category on NSDate
that that converts a NSDate
into a NSString
. It uses an NSDateFormatter
to do so. I found that allocating then deallocating the formatter each time was causing noticeable delays in my application (this category is used very frequently), so I updated my 'format' method to look like this:
- (NSString *)pretty
{
static NSDateFormatter *formatter = nil;
if (formatter == nil)
{
formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterLongStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
}
return [formatter stringFromDate:self];
}
Is this the correct way to handle a static variable in Cocoa? Is this a leak (no dealloc
after alloc
)? Does a better way exist of doing something like this? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在有效地创建一个单例。除非不会在应用程序的整个运行会话中使用它,否则不必担心内存使用。即使它只是间歇性地使用,保留一个日期格式化程序也不会成为问题。
即就像单例一样,不必担心在应用程序终止之前释放对象。
如果
pretty
被多个线程攻击(并且假设NSDateFormatter
本身是线程安全的——我没有检查文档,因此,不要写代码没有验证线程安全),那么你想要保护初始化。You are effectively creating a singleton. Unless it isn't going to be used throughout the entire running session of your application, don't worry about the memory use. Even if it is only going to be used intermittently, leaving one date formatter around isn't going to be an issue.
I.e. just like a singleton, don't worry about releasing the object prior to application termination.
If
pretty
were to be pounded on from multiple threads (and assuming thatNSDateFormatter
itself is thread safe -- I didn't check the docs and, thus, don't write the code without verifying thread safety), then you'd want to protect the initialization.我相信你应该保留格式化程序,以免它被泄露,并且下次使用格式化程序时你会遇到崩溃,也许是虚假的。
无论如何,我对类别中的 NSDateFormatter 对象执行此操作,因为我也观察到 NSDateFormatter 分配正在减慢我的应用程序的速度。
I believe you should retain the formatter lest it be leaked and you'll get a crash, perhaps spuriously, the next time the formatter is used.
For what it's worth, I do this very thing with NSDateFormatter objects in a category, as I too observed that NSDateFormatter allocation was slowing down my app.