I have just created an
@property (nonatomic, retain) NSString *var;
@implementation NSString (Name)
[self setVar:@"Its a new string"]; // Crashes here
NSLog(@"name = %@",self.var);
unrecognized selector sent to instance 0x1023641c8 2015-05-25
11:12:49.246 Tute[710:14433] *** Terminating app due to uncaught
exception 'NSInvalidArgumentException', reason:
'-[__NSCFConstantString setVar:]: unrecognized selector sent to
There are a few issues with what you're trying to do.
From Apple's Programming with Objective C documentation:
Categories can be used to declare either instance methods or class methods but are not usually suitable for declaring additional properties.
A category can add something called an associated object, but its primary purpose is to add methods.
A category instance method (one that begins with a -) operates on the instance variable that calls the method. Within the instance method, self refers to the caller instance variable, not a class (or a category property, as you attempted to access).
In your category example, you'd be calling newString from an existing NSString, like so:
NSString *myString = @"foo"; [myString newString];
In other words, the newString category extension operates on the string that called it. You can change that string, or return a different result, but the issue is that you're operating on an NSString which has no such
var property or method.
That's why you're seeing a 'No such selector message,' as NSString knows nothing about an unrelated property you happened to add to your category.
The other issue, is that you've began the method with 'new'. There are some specific naming conventions for Objective-C that have to do with memory management policy. Starting a method with alloc, new, copy, or mutableCopy implicitly tells ARC that your method (has created and) is returning a retained object. Your
newString method did not create an object.
For more information, see the Categories topic.