PDA

View Full Version : Alloc class???




larswik
Apr 17, 2008, 02:35 AM
This has me stumped and hoping to have some light shed on it.

myFraction = [Fraction alloc];
myFraction = [myFraction init];

The book says "The allco method is guaranteed to zero out all of the objects instance variables. However, that does not mean that the object has been properly initialized for use. You need to initialize an object after you allocate it."

I don't understand what they mean by "zero out". My guess would be that it means if I have any instance variables in objects they would disappear or be zeroed out??? But how can they be zeroed out if I still need to initialize them? Wouldn't they already be zeroed (not storing any variables) when the second step happens?

Thanks,

-Lars



HiRez
Apr 17, 2008, 02:54 AM
This has me stumped and hoping to have some light shed on it.

myFraction = [Fraction alloc];
myFraction = [myFraction init];

The book says "The allco method is guaranteed to zero out all of the objects instance variables. However, that does not mean that the object has been properly initialized for use. You need to initialize an object after you allocate it."

I don't understand what they mean by "zero out". My guess would be that it means if I have any instance variables in objects they would disappear or be zeroed out??? But how can they be zeroed out if I still need to initialize them? Wouldn't they already be zeroed (not storing any variables) when the second step happens?When you call init, it calls the init method of the object, which can do additional setup, such as setting default values, creating instance variables like arrays, dictionaries, or other objects, checking the system for information, loading resource files, or many other things. alloc just allocates the memory at a low level, init does most of the setup at the object level. So you need them both, and also I've never seen them done separately like you have there. You'd typically write it like:Fraction *myFraction = [[Fraction alloc] init];

larswik
Apr 17, 2008, 07:53 PM
HIREZ, thanks again. So that could be loading preference files and things like that, I understand. The book started out using that example to simplify the examples. He then wrote it the way you did and said that this is the way people do it.

I am re reading this section again tonight to I better understand it. Thanks for helping me learn!!!

-Lars