Amazon.com Widgets Program 3.2 - need to assign results of [myFraction init]?
Welcome, Guest. Please login or register.
Did you miss your activation email?
May 22, 2013, 02:52:18 PM
Home Help Search chat Login Register   
News: Read this please.The Great Kangaroo Escape Looking for reviews of the 4th ed on Amazon!   Twitter:  @skochan
                     

+  Official Forum for Programming in Objective-C (the iPhone Programming Language) - Stephen Kochan
|-+  Programming in Objective-C, 4th edition
| |-+  Chapter 3
| | |-+  Program 3.2 - need to assign results of [myFraction init]?
Pages: [1]   Go Down
Print
Author Topic: Program 3.2 - need to assign results of [myFraction init]?  (Read 513 times)
John Dallman
Newbie
*
Posts: 8






« on: June 21, 2012, 04:50:47 AM »

Program 3.2 has (with comments I added):

Code: (Objective-C)
Fraction *myFraction;                  // Note not initialised yet.
myFraction = [Fraction alloc];        // Allocate memory - inherited
myFraction = [myFraction init];      // Initialise - inherited

I understand [Fraction alloc], which allocates memory and returns a pointer to the object. That's clear. [myFraction init] initialises the object, which may not do anything in this example, but will be required for many real-world objects.

But I'm a bit puzzled by the need to assign the result of [myFraction init] to myFraction. The object already has an address, and putting in a few NSLog calls reveals that the pointer in myFraction has the same value before and after the [myFraction init] call. I can immagine scenarios where that might be necessary, but they don't seem very plausible.

Is this actually a useful convention?
Logged
John Dallman
Newbie
*
Posts: 8






« Reply #1 on: June 21, 2012, 05:51:17 AM »

And now I've read a bit further, I see where it comes from: it's a natural result of being used to writing [[Class alloc] init], and then breaking it up to be less intimidating-looking.
Logged
[I code:forFun]
Newbie
*
Posts: 12






« Reply #2 on: June 21, 2012, 05:56:39 AM »

I wonder if it could be that when you initialize the 'myFraction' object, it is stored in a new place in memory, and thus you would want to assign that newly returned address to the 'myFraction' variable.  Or maybe it is the same address, and I'm missing something else important.  Hopefully someone will chime in that knows for sure.   : )

The book says: alloc returns the address in memory of the newly created object, and init returns the initialized object.  So I think my first guess is wrong.  Still want an explanation too.
« Last Edit: June 21, 2012, 06:10:45 AM by [I code:forFun] » Logged
Pages: [1]   Go Up
Print
Jump to:  



Login with username, password and session length

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!
Entire forum contents (c) 2009 classroomM.com. All rights reserved.