Subscribe ( )

iPhone Programming Tutorials


 

Forum

You must be logged in to post Login Register

Search 

Two ways to create an object ?

User Post

3:35 am
October 23, 2008


iCoder

Derbyshire, UK

posts 10

1

One little thing is puzzling me about creating an object from your own class. What is the difference between:

myClass *myObject;

and

myClass *myObject=[[myClass alloc] init];


5:45 am
October 23, 2008


AdeC

iCoder

posts 17

2

Im a noob too so here is my view (right or wrong!)

The first example if simply a variable declaration of an object type. i.e. it has not been instatiated yet.

The second is the same but the extra bit assigns the variable (myObject) to a new instance of type myClass. So [myClass alloc] allocates the memory for the object and init is a method call on myClass to initialise it.


Hope that makes sense (and is correct :) )

6:41 am
November 7, 2008


kelvin

Noob

posts 1

3

The first line of code:

myClass *myObject;

only creates a variable that is a pointer to an object of type myClass.  In Objective-C (and C) prefixing a variable w/ an * specifies that the variable is a pointer.  However, nothing is assigned to the pointer.


In the second line of code:

myClass *myObject=[[myClass alloc] init];

an object of type MyClass has been created in memory and a pointer that points to the object's address in memory is assigned to myObject.


Don't forget that whenever you use alloc, you have to remember to call release/autorelease on the object when it's no longer being used.  For more details, look at Lecture 6 from the Stanford course:


http://twitter.com/kelvin

Search 

About the iCodeBlog forum

Most Users Ever Online:

44


Currently Online:

8 Guests

Forum Stats:

Groups: 2

Forums: 6

Topics: 419

Posts: 893

Membership:

There are 934 Members

There has been 1 Guest

There are 2 Admins

There is 1 Moderator

Top Posters:

bobcubsfan – 54

crazyiez – 30

Uhu – 17

AdeC – 17

Nick – 15

jitesh61 – 12

Administrators: Brandon (88 Posts), Collin (0 Posts)

Moderators: VertigoSol (26 Posts)



©   

  • Posted by on 6 Aug 2008 in Uncategorized
  •   |  
  •   |  
  •   |  
  • Comments Off

Comments are closed.