gpt4 book ai didi

ios - NSString 类别中的扩展属性崩溃

转载 作者:可可西里 更新时间:2023-11-01 05:11:44 26 4
gpt4 key购买 nike

我刚刚在 Category 类中为 NSString 类创建了一个 Extension

#import "NSString+Name.h"

@interface NSString(Name)

@property (nonatomic, retain) NSString *var;

@end

但是当我尝试访问类别类中的私有(private)变量时,应用程序崩溃并给出错误。

@implementation NSString (Name)

- (NSString*)newString{

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

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

return self.var;
}

@end

崩溃原因

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'

如果我能够在那个变量中赋值那么为什么它说无法识别的选择器

最佳答案

您应该使用关联对象。在下面找到对我有用的代码:

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

引用here , herehere

关于ios - NSString 类别中的扩展属性崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30431977/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com