Re: Getting a variable from another class
Re: Getting a variable from another class
- Subject: Re: Getting a variable from another class
- From: email@hidden
- Date: Tue, 14 Mar 2006 22:22:26 +1100
You can declare public ivars using the @public keyword like this
(typed in mail):
@interface MyObject {
NSString *name; //This variable is protected.
@public
NSString *publicName; //This variable is public, and can be
accessed directly by anyone
}
@end
You can also use the @defs() directive in order to access private/
protected ivars but it is not recommended in most cases.
This is not a good approach in any case.... you really shouldn't try
to access another class's instance variables directly.... @public
really should be thrown out. :P
What you want to do is declare them as @private or @protected as
normal, and provide accessor methods to access them. For example, to
subvert the example above:
@interface MyObject {
@protected
NSString *_name; //This variable is protected.
}
- (void)setName:(NSString*)name;
- (NSString*)name;
@end
@implementation MyObject {
- (void)setName:(NSString*)name {
if (name != _name) {
[_name release];
_name = [name copy];
}
}
- (NSString*)name {
return [[_name copy] autorelease];
}
@end
Basic things like this are well covered in all the Cocoa books out
there. I'd recommend you pick up at least one of them and work
through them.
Note that it's a good idea to have accessors in any class which has
even the most remote possibility of being subclassed. If that
possibility exists, all your class's methods should use those getters
in preference to accessing the instance variables directly. Thus,
subclasses can override those getters if they like. Otherwise, your
subclasses may be limited by those direct accesses and whatever model
you have for those instance variables. If they're declared @private,
your subclass may not be able to modify them at all, defeating the
purpose of inheritance in the language. Worst of all, it won't stop
stubborn people getting control - they'll just use very nasty methods
to do so.
And if you're worried about frequent use of getter methods - e.g. as
regards performance - you'll be wanting the next aisle, "C++ and
other static typed languages". :P
Wade Tregaskis
ICQ: 40056898
AIM, Yahoo & Skype: wadetregaskis
MSN: email@hidden
iChat & email: email@hidden
Jabber: email@hidden
Google Talk: email@hidden
http://homepage.mac.com/wadetregaskis/
-- Sed quis custodiet ipsos custodes?
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden