I have a very straight forward class with mostly NSString type properties. In it, I wrote a trivial implementation of the description method. I found that whenever I try to include "self" in the description, it crashes my iPhone app. An example is something such as the following:
- (NSString *)description
{
NSString *result;
result = [NSString stringWithFormat:@"me: %@\nsomeVar: %@", self, self.someVar];
return result;
}
As soon as I remove the first parameter to the format string, self, it works as expected.
self is a special variable in Objective-C, inside an instance method this variable refers to the receiver(object) of the message that invoked the method, while in a class method self will indicate which class is calling.
In some languages, for example C++ and Java, this or self is a keyword, and the variable automatically exists in instance methods. In others, for example Python, Rust, and Perl 5, the first parameter of an instance method is such a reference. It needs to be specified explicitly.
In Objective-C, any character , numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object (In this case), initialized with that value. C's type suffixes may be used to control the size of numeric literals. '@' is used a lot in the objective-C world.
In Objective-C, instance variables are commonly created with @propertys. An @property is basically an instance variable with a few extra bonus features attached. The biggest addition is that Objective-C will automatically define what's called a setter and a getter for you automatically.
Use %p
for self
, then it will display the address of self
. If you use %@
, then it will call description
on self
, which will set up an infinite recursion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With