I have just created an Extension
for NSString
class inside a Category
class
#import "NSString+Name.h"
@interface NSString(Name)
@property (nonatomic, retain) NSString *var;
@end
But when i am trying to access that private variable inside the category class the app crashes and gives the error.
@implementation NSString (Name)
- (NSString*)newString{
[self setVar:@"Its a new string"]; // Crashes here
NSLog(@"name = %@",self.var);
return self.var;
}
@end
Reason of crash
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 instance 0x1023641c8'
If i am able to assign values in that variable then why its saying unrecognized selector
You should use Associated Objects. Find below the code this worked for me:
.h
@interface NSString (Name)
@property (nonatomic, assign)NSString *var;
- (NSString*)newString;
@end
.m
static char const * const Key = "SomeKey";
@implementation NSString (Name)
- (NSString*)newString
{
self.var = @"Its a new string";
NSLog(@"name = %@",self.var);
return (self.var);
}
- (void)setVar:(NSString *)aVar {
objc_setAssociatedObject(self, Key, aVar, OBJC_ASSOCIATION_ASSIGN);
}
- (NSString*)var {
return (NSString*)objc_getAssociatedObject(self, Key);
}
Refer here, here and here
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