Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension Property Crashes In NSString Category

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

like image 676
abhishekkharwar Avatar asked Feb 11 '23 01:02

abhishekkharwar


1 Answers

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

like image 146
Vivek Molkar Avatar answered Feb 13 '23 05:02

Vivek Molkar