Field Initialization

Field Initialization

Post by Michael J. Bergi » Sat, 21 Jun 2003 12:25:42



What is the standard way for initializing fields of an object?  In Java I
can do this:

protected int age = -1;

What is the equivalent for Objective-C?

 
 
 

Field Initialization

Post by Michael As » Sat, 21 Jun 2003 12:34:19




Quote:> What is the standard way for initializing fields of an object?  In Java I
> can do this:

> protected int age = -1;

> What is the equivalent for Objective-C?

- init
{
   age = -1;
   foo = 3;
   ...

   return self;

Quote:}

Depending on your class, it may be a different init method. Or you might
put these things in +new if you're descending from Object.

Note that generally ObjC guarantees that ivars will be filled with zero
when a new object is created, so you don't need to initialize that, at
least.

There is no way to do it in the declaration of the ivar the way you seem
to have quoted for Java.

 
 
 

Field Initialization

Post by Joe Shimku » Sat, 21 Jun 2003 12:38:24




Quote:> What is the standard way for initializing fields of an object?  In Java I
> can do this:

> protected int age = -1;

> What is the equivalent for Objective-C?

-init
{
   age = -1;

Quote:}

Object allocation proceeds as:

   obj = [[class alloc] init];

--
PGP Key (DH/DSS): http://www.shimkus.com/public_key.asc
PGP Fingerprint:  89B4 52DA CF10 EE03 02AD  9134 21C6 2A68 CE52 EE1A

 
 
 

Field Initialization

Post by David Ste » Sun, 22 Jun 2003 04:53:47



> Object allocation proceeds as:

>   obj = [[class alloc] init];

Object creation normally would proceed as in:

   obj = [class new];

 
 
 

Field Initialization

Post by Christian Brunsch » Sun, 22 Jun 2003 16:02:30





>> Object allocation proceeds as:

>>   obj = [[class alloc] init];

>Object creation normally would proceed as in:

>   obj = [class new];

Which precise method of object creation is used depends on the classes in
question. The method which David Stes suggests, '[class new]', is used
mainly in older class libraries such as Stepstone's ICPak adn David Stes'
own ObjPak, whereas '[[class alloc] init]' is used in more modern classes
such as those in Apple's Foundation Kit, and in GNUStep.

Best wishes,

// Christian Brunschen

 
 
 

Field Initialization

Post by David Ste » Sun, 22 Jun 2003 16:12:43



>>Object creation normally would proceed as in:

>>   obj = [class new];

> Which precise method of object creation is used depends on the classes in
> question. The method which David Stes suggests, '[class new]', is used
> mainly in older class libraries such as Stepstone's ICPak adn David Stes'
> own ObjPak, whereas '[[class alloc] init]' is used in more modern classes
> such as those in Apple's Foundation Kit, and in GNUStep.

That's really a step backwards.  It's good practice to avoid +alloc/-init
and use the superior +new mechanism.
 
 
 

Field Initialization

Post by Michael J. Bergi » Mon, 23 Jun 2003 05:34:32





>>> Object creation normally would proceed as in:

>>>   obj = [class new];

>> Which precise method of object creation is used depends on the classes in
>> question. The method which David Stes suggests, '[class new]', is used
>> mainly in older class libraries such as Stepstone's ICPak adn David Stes'
>> own ObjPak, whereas '[[class alloc] init]' is used in more modern classes
>> such as those in Apple's Foundation Kit, and in GNUStep.

> That's really a step backwards.  It's good practice to avoid +alloc/-init
> and use the superior +new mechanism.

 I'm reading a book on the Cocoa framework for OS X and they state in the
book that +new is an old deprecated method for creating objects.  So I'm a
bit confused, is +new something older than the +alloc/-init method that is
considered better or is there another ObjC framework that +new is the newer
way of creating objects?
 
 
 

Field Initialization

Post by Christian Brunsch » Mon, 23 Jun 2003 05:46:08





>>>Object creation normally would proceed as in:

>>>   obj = [class new];

>> Which precise method of object creation is used depends on the classes in
>> question. The method which David Stes suggests, '[class new]', is used
>> mainly in older class libraries such as Stepstone's ICPak adn David Stes'
>> own ObjPak, whereas '[[class alloc] init]' is used in more modern classes
>> such as those in Apple's Foundation Kit, and in GNUStep.

>That's really a step backwards.  It's good practice to avoid +alloc/-init
>and use the superior +new mechanism.

David Stes' aversion to Apple's frameworks is well-known, but alas not
based in any sound reasoning - the astute reader will note that David Stes
is making an assertion but without offering any supporting evidence or
reasoning. And while my original post on this subject simply noted that
there are two prevalent paradigms for object creation, I shall offer some
support for why +new is _not_ the 'superior mechanism'.

Separating object allocation from initialisation is in fact a very sound
practice, which has several advantages:

1) allocation and initialisation are conceptually different things, and as
such should be kept separate

2) there is no reason why allocation and initialization need to happen
together. For instance, it may make a lot of sense to pre-allocate a
number of objects but only initialize them as needed, for instance - with
the '+new' approach this is difficult

3) Just because allocation and initialization are kept separate, doesn't
mean that a 'unified' interface can now _also_ be presented. In fact,
Apple's Foundation library implements
+ new { return [[self alloc] init]; }
for backwards compatibility

4) In order to initializa an object within a +new method, you either have
to swizzle the 'self' pointer within +new - in the process changing 'self'
from referring to a class, to referring to an instance, which is not very
conceptually clean:
+ new { self = [super new]; foo = 1; return self; }
Or you have to use a separate variable to hold the instance to be
returned:
+ new { id newInstance = [super new]; newInstance->foo = 1; return self; }
Of course, the immediate solution to this inelegance presents itself: use
a separate method to initialize the fresh isntance:
+new { return [[self alloc] init]; }
... which brings us full circle back to the Foundation way of doing
things.

5) There's nothing that you can do with the '+new' approach that you can
not do with the +alloc/-init approach. The converse, however, is not true.  

And while this isn't a technical argument per se, you might also want to
consider that Apple is probably the biggest single Objective-C developer
today, and that Apple's toolkits are the most widely-used ones, both in
the shape of Apple's own implemenation, and in the shapes of open-source
tookits that reimplement them. Apple, and NeXT before them, changed from
using +new to using +alloc/-init for a reason:  specifically, they found
+alloc/-init to wok better than +new.

Best wishes

// Christian Brunschen

 
 
 

Field Initialization

Post by Christian Brunsch » Mon, 23 Jun 2003 06:05:13







>>>> Object creation normally would proceed as in:

>>>>   obj = [class new];

>>> Which precise method of object creation is used depends on the classes in
>>> question. The method which David Stes suggests, '[class new]', is used
>>> mainly in older class libraries such as Stepstone's ICPak adn David Stes'
>>> own ObjPak, whereas '[[class alloc] init]' is used in more modern classes
>>> such as those in Apple's Foundation Kit, and in GNUStep.

>> That's really a step backwards.  It's good practice to avoid +alloc/-init
>> and use the superior +new mechanism.

> I'm reading a book on the Cocoa framework for OS X and they state in the
>book that +new is an old deprecated method for creating objects.  So I'm a
>bit confused, is +new something older than the +alloc/-init method that is
>considered better or is there another ObjC framework that +new is the newer
>way of creating objects?

There are several different Objective-C class libraries. Older ones, such
as Stepstone's defunct ICPak (of which David Stes' ObjPak is a
reimplementation), use +new.

NeXT based their initial class library on Stepstone's, but extended it to
separate +new into +alloc/-init , with a backwards-compatible
implementation of +new as '+new { return [[self alloc] init]; }'. Code
examples used both +new and +alloc/-init fairly interchangably.

However, NeXT listened to their own experiences and that of their clients,
and developed OpenStep (together with Sun), which contains Foundation Kit
and Application Kit - and which moved officially away from +new, to using
either +alloc/-init explicitly, or using the specific convenience methods
offered by each class, such as NSString's +stringWithFormat:, NSArray's
+arrayWithObjects:, and so on. Foundation Kit has since evolved further
within the realm of Apple's Cocoa, and while it still includes the same
legacy implementation of '+new { return [[self alloc] init]; }', within
Cocoa, +new is definitely both old and deprecated.

Of course, if you're using a different class library - such as David Stes'
ObjPak - you should generally use an object creation paradigm that matches
the class library, which in the case of ObjPak will be +new.

Best wishes,

// Christian Brunschen

 
 
 

Field Initialization

Post by David Ste » Mon, 23 Jun 2003 06:26:31



Quote:

> I'm reading a book on the Cocoa framework for OS X and they state in the
> book that +new is an old deprecated method for creating objects.

It's definitely not true;

Actually their message is not always coherent since sometimes they claim
it is "deprecated" or "obsolete" and on other occassions they will swear
that nothing has changed and that +new works.

Quote:> So I'm a
> bit confused, is +new something older than the +alloc/-init method that is
> considered better or is there another ObjC framework that +new is the newer
> way of creating objects?

+new is the default way of creating objects.  In some circumstances, other
ways of creating objects can exist as well, of course.  It's just that there's
no "better" way to create a simple Object than with +new, for simple purposes.
 
 
 

Field Initialization

Post by Christian Brunsch » Mon, 23 Jun 2003 06:59:01





>> I'm reading a book on the Cocoa framework for OS X and they state in the
>> book that +new is an old deprecated method for creating objects.

>It's definitely not true;

David Stes is incorrect. Within the Cocoa framework, using +new is
definitely old and deprecated.

Quote:>Actually their message is not always coherent since sometimes they claim
>it is "deprecated" or "obsolete" and on other occassions they will swear
>that nothing has changed and that +new works.

There is nothing incoherent.

+new is old and deprecated. The advice is: don't use it.

However, if you absolutely _want_ or _have_ to use +new ... well, the
implementation of +new which _is_ included in Foundation _works_, for
reasons of backwards compatibility with legacy code.

Quote:>> So I'm a
>> bit confused, is +new something older than the +alloc/-init method that is
>> considered better or is there another ObjC framework that +new is the newer
>> way of creating objects?

>+new is the default way of creating objects.  In some circumstances, other
>ways of creating objects can exist as well, of course.  It's just that there's
>no "better" way to create a simple Object than with +new, for simple purposes.

David Stes' assertion is false.

Object creation and the mechanisms for it are not mandated by the
objective-C language, but by the class library you use. Cocoa, while
_offering_ a +new method for backwards compatibility with legacy code
developed to other class lbiraries, prefers to use the +alloc/-init way of
allocating objects. I've just detailed the advantages of separating
objecct allocation and initialisation, in a separate post. But to
summarize: Everything that you can do with +new, you can easily do with
+alloc/-init. But there are things that you can do easliy with
+alloc/-init, that you can _not_ do easily with +new. This, to me, makes
+alloc/-init inherently superior to +new.

Best wishes,

// Christian Brunschen

 
 
 

Field Initialization

Post by Timoth » Mon, 23 Jun 2003 08:27:26


        Perhaps I'll jump in. :-)

        I'm new to Objective-C programming, but not to OO programming.  I have a
solid decade of experience.  I've also taken a number of classes on
Argumentation.

        Just to level the field: both Christian Brunschen and David Stes make
unsubstantiated claims; Christian Brunschen just uses a lot more text to
do so.  ;-}

        I must admit I find the need to use a two-step procees to create an
object a bit confusing.  Whereas there may be a justifiable reason for it,
I still can not think of one.  One of the statements below alludes to
pre-allocating objects.  When would this be advantageous?  It is not that
I do not believe you, I just can't think of a situation where it would be
handy.

        If the default library provides a 'new' message that does a 'alloc' +
'init', I would think that would be the better one to use, and to do them
seperatly only when there is an actual need.  The fact that a 'new' simply
does a 'alloc' + 'init' is besides the point.

        In support of this position, my argument is that
obj = [class new]
vs.
obj = [[class alloc] init]
is not only easier to read, but less typing.  And less typing means fewer
bugs, if only from typo's.

        I would be interested to know what percentage of code ever does anything
with an object between 'alloc' and 'init'?

        When something is redundant, it aught to be eliminated.  

        So, to summerize, allow for both, but optimize for the one that will be
used most.

On 21 Jun 2003 20:46:08 GMT





> >>>Object creation normally would proceed as in:

> >>>   obj = [class new];

> >> Which precise method of object creation is used depends on the
> >classes in> question. The method which David Stes suggests, '[class
> >new]', is used> mainly in older class libraries such as Stepstone's
> >ICPak adn David Stes'> own ObjPak, whereas '[[class alloc] init]' is
> >used in more modern classes> such as those in Apple's Foundation Kit,
> >and in GNUStep.

> >That's really a step backwards.  It's good practice to avoid
> >+alloc/-init and use the superior +new mechanism.

> David Stes' aversion to Apple's frameworks is well-known, but alas not
> based in any sound reasoning - the astute reader will note that David
> Stes is making an assertion but without offering any supporting evidence
> or reasoning. And while my original post on this subject simply noted
> that there are two prevalent paradigms for object creation, I shall
> offer some support for why +new is _not_ the 'superior mechanism'.

> Separating object allocation from initialisation is in fact a very sound

> practice, which has several advantages:

> 1) allocation and initialisation are conceptually different things, and
> as such should be kept separate

> 2) there is no reason why allocation and initialization need to happen
> together. For instance, it may make a lot of sense to pre-allocate a
> number of objects but only initialize them as needed, for instance -
> with the '+new' approach this is difficult

> 3) Just because allocation and initialization are kept separate, doesn't

> mean that a 'unified' interface can now _also_ be presented. In fact,
> Apple's Foundation library implements
> + new { return [[self alloc] init]; }
> for backwards compatibility

> 4) In order to initializa an object within a +new method, you either
> have to swizzle the 'self' pointer within +new - in the process changing
> 'self' from referring to a class, to referring to an instance, which is
> not very conceptually clean:
> + new { self = [super new]; foo = 1; return self; }
> Or you have to use a separate variable to hold the instance to be
> returned:
> + new { id newInstance = [super new]; newInstance->foo = 1; return self;
> } Of course, the immediate solution to this inelegance presents itself:
> use a separate method to initialize the fresh isntance:
> +new { return [[self alloc] init]; }
> ... which brings us full circle back to the Foundation way of doing
> things.

> 5) There's nothing that you can do with the '+new' approach that you can
> not do with the +alloc/-init approach. The converse, however, is not
> true.  

> And while this isn't a technical argument per se, you might also want to
> consider that Apple is probably the biggest single Objective-C developer
> today, and that Apple's toolkits are the most widely-used ones, both in
> the shape of Apple's own implemenation, and in the shapes of open-source
> tookits that reimplement them. Apple, and NeXT before them, changed from
> using +new to using +alloc/-init for a reason:  specifically, they found
> +alloc/-init to wok better than +new.

> Best wishes

> // Christian Brunschen

 
 
 

Field Initialization

Post by Michael As » Mon, 23 Jun 2003 10:52:41




>    I must admit I find the need to use a two-step procees to create an
> object a bit confusing.  Whereas there may be a justifiable reason for it,
> I still can not think of one.  One of the statements below alludes to
> pre-allocating objects.  When would this be advantageous?  It is not that
> I do not believe you, I just can't think of a situation where it would be
> handy.

Here's why there's a two-step process in Cocoa.

There is more than one +alloc message. By default, NSObject provides
+alloc and +allocWithZone:, which lets you decide which memory zone to
put the object in. Now, zones have kind of fallen out of use, but it's
still there. Of course, an enterprising developer could provide other
+alloc... methods, for example something that caches instances instead
of deallocating and reallocating them, for classes that are commonly
destroyed and recreated.

There is more than one -init message. You have -init, and then all the
class-specific -init methods, like -initWithString:, -initWithArray:,
and so on and so forth.

By combining allocation and initialization into one step, you have to
write out all the *combinations* of the above. You'd need
+newWithString:, +newWithString:withZone:, or whatever you want to call
it, and so on. A large explosion in the number of methods.

One other reason, is that initialization in a class method doesn't
really make a lot of sense. You either have to message the new object
for every initialization, which many people see as being inconvenient or
whatever (although it's good practice!), or you have to access you new
object's ivars directly, or you do an ugly hack such as assigning self.

I'm not trying to actually advocate alloc/init, but merely explain the
reasons why it exists.

 
 
 

Field Initialization

Post by Charlton Wilbu » Mon, 23 Jun 2003 10:53:22



>    If the default library provides a 'new' message that does a
> 'alloc' + 'init', I would think that would be the better one to use,
> and to do them seperatly only when there is an actual need.  The
> fact that a 'new' simply does a 'alloc' + 'init' is besides the
> point.

There is no default library for Objective-C.

When you use Cocoa or Foundation Kit, you should use [[Object alloc]
init], or a convenience method such as [Object newWithValue: foo].
That is what is documented as the correct idiom in that library, with
the +new method explicitly kept solely for compatibility with older
code.

When you use a library such as David Stes's, which uses [Object new]
as the correct idiom, you should use [Object new].

Which one of these is the Right Thing is undecidable, but that doesn't
stop millions of electrons from dying for the cause all the same.

Charlton

 
 
 

Field Initialization

Post by Christian Brunsch » Mon, 23 Jun 2003 17:56:25




>    Perhaps I'll jump in. :-)

>    I'm new to Objective-C programming, but not to OO programming.  I have a
>solid decade of experience.  I've also taken a number of classes on
>Argumentation.

>    Just to level the field: both Christian Brunschen and David Stes make
>unsubstantiated claims; Christian Brunschen just uses a lot more text to
>do so.  ;-}

*heh* Would you please explain which of my claims aren't substantiated in
some fashion? I've tried to offer explanations or reasons for all my
opinions, and I'd really like to know where, and how, I've failed to do
so. (I have not studied argumentation or rhethorics or anything similar.)

Quote:>    I must admit I find the need to use a two-step procees to create an
>object a bit confusing.  Whereas there may be a justifiable reason for it,
>I still can not think of one.  One of the statements below alludes to
>pre-allocating objects.  When would this be advantageous?  It is not that
>I do not believe you, I just can't think of a situation where it would be
>handy.

Consider a piece of software where you *know* you will be repeatedly using
objects of a specific class, for a short time each. If object allocation
is tightly coupled with initialization, then you have to use the
underlying allocation mechanism every time - and such mechanisms are
generally written to have reasonable performanc for a wide range of sizes
of memory allocation requests; which means they will make tradeoffs. We,
however, know that we will be allocating and freeing a number of memory
blocks of one specific size, over and over - and it's easy enough to write
a small, bespoke memory allocator to handle that case *very* efficiently,
such as by allocating a multiple-object-sized memory chunk in advance and
parceling out parts of that as needed.

Quote:>    If the default library

There is no one 'default library' in Objective-C.

Quote:>provides a 'new' message that does a 'alloc' +
>'init', I would think that would be the better one to use, and to do them
>seperatly only when there is an actual need.  The fact that a 'new' simply
>does a 'alloc' + 'init' is besides the point.

In fact, in Cocoa, most object allocation is *not* done by explicitly
calling +alloc/-init, but instead by calling class methods like NSArray's
+arrayWithObjects: , NSString's +stringWithFormat: , NSDictionary's
+dictionaryWithObjectsAndKeys: and so on. The precise implementation of
these methods is indeed beside the point of their use.

The point is that in Cocoa, there are _two api:s_ exposed regarding object
allocation and initialization:

1) convenience class methods are exposed for easy and straightforward
   creation of objects

2) +alloc (and friends) / -init (and friends) are exposed to class
   implementors, and to advanced user of classes who want to access the
   extra functionality offered by the separation between allocation and
   initialization

This means that there's something for everyone: Both for those who want
one simple method to create an object, and for those who want access to
the underlying implementation. Essentially, this approach offers the best
of both worlds.

Quote:>    In support of this position, my argument is that
>obj = [class new]
>vs.
>obj = [[class alloc] init]
>is not only easier to read, but less typing.  And less typing means fewer
>bugs, if only from typo's.

Here I simply have to disagree: 'less typing' doesn _not_ mean 'fewer
bugs'. Usually, 'less typing' is achieved by using names that are less
clear, less descriptive - and thus, more prone to misunderstanding or
misreading. So while there may be less _typing_ involved, less descriptive
and readable names tend to invite more _logical_ errors. And keep in mind
that whereas compilers are excellent at finding typos, logical errors have
to be found by more traditional debugging techniques - by the developers
themselves.

And keep in mind that in Cocoa, most object allocation is not actually
done by calling +alloc/-init explicitly, but by calling one of the
convenience methods described above - which means that the actual code is
going to be akin to
Foo *foo = [Foo fooWithBar:bar];
which is certainly just as readable.

Quote:>    I would be interested to know what percentage of code ever does anything
>with an object between 'alloc' and 'init'?

As was mentioned in another post, there are actually different allocation
methods available in Cocoa. It's not the point that something may
necessarily be done with an object between object allocation and object
initialization; the point is that when you have both a variety of
allocation methods _and_ a variety of initliazation methods, then in order
to offer the complete gamut of options, one would have to create one
different +new-style method for every possible combination of object
allocation and initialization - and even if that was done, it would mean
that that set of combinations was essentially static, with no easy way to
add more allocation methods (or eveninitialization methods) into the mix.

Quote:>    When something is redundant, it aught to be eliminated.

But when it's _not_ redundant, it should not be.

Quote:>    So, to summerize, allow for both, but optimize for the one that will be
>used most.

Ah, but if you _eliminate_ the separation between +alloc and -init as you
advocate above, then you actually _do not_ 'allow for both' as you _also_
suggest.

Of course, Cocoa does already 'allow for both', as has been described.

Best wishes,

// Christian Brunschen

 
 
 

1. field data member initialization

Hello,

  how do I initialize field data member?

class MyClass
{
  int field[2];
  MyClass(void);

MyClass::MyClass(void): field({0, 0}) {};

nor

MyClass::MyClass(void): field[0](0), field[1](0) {};

is functional.

                             Thanks Ales

2. selecting the value of an element with a specific value

3. ODBC, Serial Fields (aka "Counter Fields"), and Insert

4. Oracle to SQL Server using JDBC

5. Tabing field to field

6. COMBINING VARIABLES

7. Newbie Update field in DB using AutoNumber field

8. IBM doesn't know about FDISK - I'm in big trouble!

9. Array initialisation in initialisation list

10. Initialization lists vs. assignment initialization

11. vector field

12. Set a input field control to overwrite

13. static field looses colors