Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialKuan Chung Chang
5,607 PointsWhat's the difference between these 2 description?
- NSNumber *mike; mike = [[NSNumber alloc] initWithInt:23]; 2.NSNumber *mike = @23;
It looks like they can get the same result(mike = 23), can anyone told me the difference?
2 Answers
Stepan Ulyanin
11,318 PointsHi, well as you remember Amit mentioned that everything in Objective-C is a pointer, so what is happening when you allocate and initialize a variable:
NSNumber *mike = [[NSNumber alloc] initWithInt:23];
Notice that mike is only a pointer to a particular cell in memory, then you use the class method on NSNumber alloc
, so alloc
will allocate memory for some data (in this case it is NSNumber data type) and return it, so:
[NSNumber alloc]
will return a memory address something like 0x00ab1628ff
and then notice that we call another method on the memory that has been allocated for us:
[[...] initWithInt:23]
- here you initialize the variable using the memory that has been allocated for it and putting some data that is of type NSNumber
and was made with an integer into that memory cell.
But the funniest part is that you can use:
NSNumber *mike = @23
- here @
which is specific to Objective-C only does all the heavy lifting for your manual labor, allocates memory and initializes the variable (putting the data into the memory cell) automatically for you, hope it helps
Kuan Chung Chang
5,607 PointsWow! your description is very clear to me, I guess that I can use NSNumber *mike = @23; instead of NSNumber *mike = [[NSNumber alloc] initWithInt:23]; to make the code more readable to me :)
Thanks Stepan!