Question

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?

Was it helpful?

Solution

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/

OTHER TIPS

Since convenience creators are not always available, i.e.:

self.minutesLeft = [NSNumber numberWithInt:number];

another pattern is common, if you want an autoreleased object when there is no convenience creator available:

self.minutesLeft = [[[NSNumber alloc] initWithInt:number] autorelease];

or finally

NSNumber * n = [[NSNumber alloc] initWithInt:number];
self.minutesLeft = n;
[n release], n = 0;

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top