1

I see code like this:

@synthesize dataController = _dataController;

What is the purpose of this in a view controller?

Mattbettinson
  • 27
  • 2
  • 8
  • 1
    see here: http://stackoverflow.com/questions/2114587/iphone-ivar-naming-convention -- Looks a bit different than your question though. I'm also wondering why some people also declare an iVar at the same time, when you can perfectly use the property in the class... – allaire Apr 14 '12 at 21:30
  • Using `=` with `@synthesize`, allows you to create property names that aren't the same as the actual iVar. In your example, the author uses the style of putting a `_` before private variables. However, calling `[myClass _iVar]` doesn't look as nice as `[myClass iVar]`, so putting `@synthesize _dataController = dataController` allows `_dataController` to be accessed as `dataController` from other classes, making it a little more readable. – wquist Apr 14 '12 at 22:13

4 Answers4

2

If your class needs to store values, it needs someplace in memory to store this data. An instance variable reserves memory for the data your class needs.

Let's assume you want to add a place for a string or int variable. You can use an instance variable to reserve that memory for the lifetime of the object. Each object will receive unique memory for its variables.

It's much like a C struct:

struct t_something {
  int a; int b;
};

The struct declares two fields (a and b). Each value may be read and written to, and the struct is large enough to hold its fields.

justin
  • 104,054
  • 14
  • 179
  • 226
0

There is a large amount of info here: iPhone ivar naming convention

One other thing to keep in mind:

Using an instance variable instead of the property in your class bypasses any side effects of the property implementation (retain, copy, etc.) that would normally automatically occur.

This can be especially important if you have written a custom property implementation that you wish to bypass.

Community
  • 1
  • 1
0

I use it for fast access to data, properties need to write "self." before, vars don't.

m8labs
  • 3,671
  • 2
  • 30
  • 32
  • You don't have to write self. to access a property if there is no other iVar with the same name. – allaire Apr 14 '12 at 21:40
  • Yes, I forget about it, but I think it's very, very bad style not to write self. with properties. So, we have nice ability to differ property from data vars quickly when reading code. – m8labs Apr 14 '12 at 21:56
  • 1
    @allaire: Yes, you do. When you omit `self`, you're directly accessing the ivar — if you don't specify an ivar name, an ivar with the same name is used. – Chuck Apr 15 '12 at 08:05
-1

An instance is a real-time variable value holder, which contains in the class. An object is a blueprint of the class that handles the instance. Memory allocation and reallocation capabilities in instance

Daniel
  • 783
  • 1
  • 5
  • 16