Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't include "self" in Objective-C description method?

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.

like image 662
Coocoo4Cocoa Avatar asked May 23 '09 07:05

Coocoo4Cocoa


People also ask

What is self in Objective-C?

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.

Is there a self keyword in C++?

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.

What does @() mean in Objective-C?

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.

How do you declare an instance variable in Objective-C?

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.


1 Answers

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.

like image 135
dreamlax Avatar answered Oct 29 '22 11:10

dreamlax