iOS Tips: Don't use 'description'
What is wrong with the following piece of code ?
@interface MyArticleClass : NSObject
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *description;
@end
The title of this post has already given this away. We can’t use description as a property name and here’s why.
NSObject
already has a description
method which by default returns a string with the object name and memory address. Subclasses can override this method to return a more descriptive string. This can help print out useful information to aid debugging when using NSLog
or the po
in the debug console.
Having a description
property on the subclass MyArticleClass
in the example above is just asking for trouble. The code will have no issues compiling, it will probably work fine until you use it with core data. See this stackoverflow link. The general rule is to avoid using property names of methods or properties declared in parent classes unless its specifically to override them.
That being said, do make use of description to aid your debugging
Interface
@interface MyArticleClass : NSObject
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *articleDescription;
@end
Implementation
@implementation MyArticleClass
- (NSString *)description
{
return [NSString stringWithFormat:@"MyArticleClass: %p %@ - %@",self, self.title, self.articleDescription];
}
@end
Usage
MyArticleClass *article = [[MyArticleClass alloc] init];
article.title = @"iOS Tips";
article.articleDescription = @"The first iOS tips post!";
NSLog(@" %@ ", article);
Result
MyArticleClass: 0x74d5920 iOS Tips - The first iOS tips post!