And a disclaimer: these posts are for someone exactly like me. In fact, they are for me. If you know anything about Cocoa, you are probably wasting your time. But if you're struggling with the documentation and overly complex examples, you've come to the right place.
NSNumber
NSNumber provides a way of storing a value (the docs say: "a signed or unsigned char, short int, int, long int, long long int, float, or double or a BOOL." You can't do math with these things, but you can store them in an array and write them to disk, very useful indeed. You can also compare them, and get them back out again when you need them.So I had a couple of questions:
• what 's the difference between the class method and instance method for getting a new number?
+ (NSNumber *)numberWithInteger:(NSInteger)value
- (id)initWithInteger:(NSInteger)value
• why is there a method for int and also a method for integer?
• I saw a discussion of something funny going on with NSNumber, and I thought I'd explore it. See below.
You can copy and paste the code listing into a text file. Save it and compile it from the command line as indicated. In the first part, we do alloc..init. That means in the classical memory environment (as here b/c we compiled without garbage collection), we own the NSNumber and
Curiously, this freshly minted NSNumber has a retainCount of 2. I thought we owned it, but it looks like we we're just renting...
After that we get a second NSNumber using the same integer value (1) by the class "convenience" method. This code fails unless we set up the autorelease pool beforehand. Something very wild happens. It has a retainCount of 3, and remarkably, the retainCount of our first NSNumber has also gone up. Can you guess?
We really shouldn't, but let's do a retain on the first number in the second part of the code. Once again, the retainCount of both NSNumbers is incremented. What's going on? A peek at the addresses of the objects reveals the magic: they actually are the same thing! Here's the output (stripped of the date/time info from NSLog):
The last line of the output results from the third section of code. We go through the integers one-by-one until the NSNumbers we get from calls to the class method are different. This happens when i = 13. For 0 through 12 they are identical. It's a baker's dozen.
[blogger is doing weird sh*t with the indentation on my code. Sorry about that. Let me know if something doesn't work for you.] And let me know if you have a better idea about code posting in html.