Reputation: 66032
I have an objective-c class with member variables. I am creating getters and setters for each one. Mostly for learning purposes. My setter looks like the following:
- (void) setSomething:(NSString *)input {
something = input;
}
However, in C++ and other languages I have worked with in the past, you can reference the member variable by using the this
pointer like this->something = input
. In objective-c this is known as self
. So I was wondering if something like that is possible in objective-c? Something like this:
- (void) setSomething:(NSString *)input {
[self something] = input;
}
But that would call the getter for something
. So I'm not sure. So my question is:
Is there a way I can do assignment utilizing the self pointer?
If so, how?
Is this good practice or is it evil?
Thanks!
Upvotes: 3
Views: 1089
Reputation: 54445
You're effectively using "self" implicitly when you use...
something = input;
...if there's no local "something" variable. (i.e.: There's really no need to add an explicit "self", and people generally don't.)
That said, your code sample isn't retaining the input, so it probably isn't going to do what you expect (well, not for long without crashing in the case of an NSString).
As such, if you really want to write your own setters (the Objective-C property/synthesize set up is a lot less hassle), you'll need to use something like:
- (void) setSomething:(NSString *)input {
if(something != input) {
[input retain];
[something release];
something = input;
}
}
Upvotes: 2
Reputation: 400622
Yes, it uses the same syntax as C++, with self
in place of this
:
self->something = input;
Upvotes: 4