如何在不执行 alloc 的情况下获取 NSNumber,以便它响应 initWithInt?
我的理解是,诸如 [nsnumber initWithInt] 之类的“方便”方法应该创建指定类的副本,并初始化为所需的值。
minutesLeft=[NSNumber initWithInt:((timeLeft)%60)];
Timeleft 是一个整数,因此 initWithInt 应该可以工作,结果应该是 分钟Left (设置为保留的属性)应该接收并保留新的 NSNumber。问题是,由于某种原因,我收到“NSNumber 可能不会响应 +initWithInt”的警告。因为有问题的属性设置为保留,所以我不想使用 [nsnumber alloc] initwithint,因为那样我必须释放它。
有什么想法吗?
My understanding is that a 'convenience' method such as [nsnumber initWithInt] should create a copy of the indicated class, initialized to the desired value.
minutesLeft=[NSNumber initWithInt:((timeLeft)%60)];
Timeleft is an integer, so initWithInt should be working, and the result should be that minutesLeft (a property set to retain) should be receiving, and then retaining, the new NSNumber. The problem is that for some reason, I'm getting the warning that 'NSNumber may not respond to +initWithInt'. Because the property in question is set to retain, I don't want to use [nsnumber alloc] initwithint, because then I have to release it.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的意思是:
[NSNumber numberWithInt:number];
请记住,该值是自动释放的,因此您可能需要保留它。如果您使用的是 Mac,请不要担心。
当你想要这样的东西但其他类上没有它时,你总是可以编写一个类别来扩展任何可可类。
http://cocoadevcentral.com/d/learn_objectivec/
Do you mean like:
[NSNumber numberWithInt:number];
Keep in mind this value is autoreleased so you might need to retain it. If you are on Mac don't worry about it though.
When you want something like this but it isn't there on other classes you can always write a category to extend any cocoa class.
http://cocoadevcentral.com/d/learn_objectivec/
由于便利创建者并不总是可用,即:
另一种模式很常见,如果您在没有便利创建者可用时想要一个自动释放的对象:
或最后
此外,我认为假设应编写新代码以与托管内存(未垃圾收集)。如果您在托管内存上下文中使用该程序,那么跟踪已发送额外自动释放的对象可能会非常耗时。可能会有许多难以跟踪或重现的错误(包括重大泄漏)。编写引用计数接口/例程应该是第二天性 - 当您编写类时很容易编写,而不是稍后再添加(阅读:您必须阅读大量代码,这非常耗时) - 然后你必须测试、测试、测试所有更新的程序。
Since convenience creators are not always available, i.e.:
another pattern is common, if you want an autoreleased object when there is no convenience creator available:
or finally
Furthermore, I think it's a good idea to assume new code should be written to be compatible with managed memory (not garbage collected). Tracking down an object which has been sent an extra autorelease can be horribly time consuming, should you ever use the program in a managed memory context. There will likely be many bugs which are difficult to track or reproduce (including major leaks). Writing ref counting interfaces/routines should be second nature - it's very easy to write when you are writing the class, as opposed to tacking it on later (read: you'll have to read through a lot of code which is very time consuming) - then you'll have to test, test, test all the updated programs.