0

Sometimes I see object pointers set, without allocating or initializing them. For example:

MyObject *object;

And then it will be later assigned to a value. My guess is that this is more efficient, or a good way to not use memory until it's needed?

I've found answers like this one that touch on it, but I don't have much background in C++ or Java. If there are any Redditers out there, or someone who could Explain Like I'm Five, I'd love that.

Community
  • 1
  • 1
ArielSD
  • 679
  • 8
  • 23
  • 1
    The question you linked is for C++, not Objective-C. The discussion doesn't fully apply to Objective-C. – rmaddy May 11 '17 at 13:57
  • Ok. I think you are aware about references from C,C++. You are just going to assign reference of an object to another. In iOS an object will be in memory if and only if atleast one reference is available. So creating a new reference will put object into memory until you are not releasing it – Gagan_iOS May 11 '17 at 13:58
  • 3
    There's a problem with the title of your question that is important when trying to understand this. The line you quote **is not** "Declaring An Objective-C Object" at all. It is defining a variable that may point to such an object if one is created and has its address assigned to the pointer. (Informally, we talk about the pointer as if it were the object fairly often but it's confusing for someone learning about the subject.) – Phillip Mills May 11 '17 at 14:14

1 Answers1

1
MyObject *object;

That declares a reference to an object. It doesn't declare an object at all, nor does it allocate any memory.

You can easily copy an already existing reference to that reference, no need to allocate anything first:

object = [myThingamabob giveMeAnObject];

It is identical to doing this in C:

int main(int argc, char *argv[]) {
  char *dogstring;
  dogstring = argv[0];
}

In ELI5 terms:

Say you have a business card holder. It is empty. You don't have to put a blank card in it before putting a card given to you by another person. You can just put the received card straight into the box.

bbum
  • 160,467
  • 23
  • 266
  • 355