On 12 Feb 2009, at 1:42 am, Jason Wiggins wrote:

How do I access the ivars of modelObject1 from modelObject2 and vice versa?


Others have had plenty of useful advice to give on the general question, but in your original, this stood out for me.

The answer here is: YOU DON'T. ivar stands for "instance variable" and it should be private to the object that defines them. No other object should ever access an object's ivars. This is the principle of encapsulation. What you may have meant is how do I access another object's *properties*. That's different. An object's properties are not equivalent to its ivars. Often properties are implemented using ivars, but they are not the same thing - how a property is implemented is an internal detail of the object that has that property.

It's important to understand this difference, which is why I'm harping on about it - terminology matters.

example:

An object has a property 'name' that returns a string. It matters not to another object how 'name' is generated, it could be:

- (NSString*) name
{
     return mName;      // return the ivar that holds the name
}

or equally validly:

- (NSString*) name
{
return [NSString stringWithFormat:@"My name is: %@", [[MyNameHelperClass stringElement] capitalizedString]];
}


In other words, the property is 'name' but it has nothing necessarily to do with ivars.

To help enforce this, it's usually a good idea to set all ivars of an object to be private using @private in your class definition. This forces you to ensure there are accessors for every one that you need to expose as a property. Even subclasses are then forced to use the property accessors and not the ivars (though that is occasionally inconvenient and not what you want, but those cases are the exception not the rule).

Sorry for the somewhat tangential reply - it's not answering your main question, but remember, terminology matters. Incorrect use of terminology (as in conflating 'ivar' with 'property') typically reveals incorrect or sloppy thinking about concepts.

--Graham


_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to