Failure in extension properties in NSString category

I just created a class Extensionfor NSStringinside a classCategory

#import "NSString+Name.h"

@interface NSString(Name)

@property (nonatomic, retain) NSString *var;

@end

But when I try to access this private variable inside the category class, the application crashes and throws an error.

@implementation NSString (Name)

- (NSString*)newString{

    [self setVar:@"Its a new string"];    // Crashes here

    NSLog(@"name = %@",self.var);

    return self.var;
}

@end

Cause of the accident

unrecognized selector sent to instance 0x1023641c8 2015-05-25 11:12: 49.246 Tute [710: 14433] *** Application termination due to a non-displaying "NSInvalidArgumentException" exception, reason: '- [__ NSCFConstantString setVar:]: unrecognized selector, posted as an example 0x1023641c8 '

If I can assign values ​​to this variable, then why its saying of an unrecognized selector

+4
source share
3 answers

, .

  • .

Apple [ Objective C] [1] :

, .

-, , .

  1. Self

(, a -) , . self , ( , ).

newString NSString, :

NSString *myString = @"foo";
[myString newString];

, newString , . , , NSString, var.

" ", NSString , .

  1. , new, ARC.

, "". Objective-C, . alloc, new, copy mutableCopy ARC, ( ) . newString .

+2

. , :

.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);
}

,

+4

use _ instead of self, it will go into an infinite loop

- (NSString*)newString
{

    _var = @"Its a new string";
    NSLog(@"name = %@",_var);

    return (self.var);
}
+2
source

All Articles