OGeek|极客世界-中国程序员成长平台

标题: ios - 为什么我的对象会发生意外变化? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 03:32
标题: ios - 为什么我的对象会发生意外变化?

我有一个非常基本的示例,我正在将一些数据从 JSON 读取到一个类中,并且我的对象正在以某种方式损坏。我怀疑我遗漏了有关属性/ARC 工作方式的一些细节,但我不确定它是什么,或者我将如何追踪它。

我已经减少了我的原始代码,这样问题就很明显了。然而,这意味着不清楚我为什么要使用自定义属性等 - 我的真实代码在那里有更多功能......

这个问题可以在 Test.m 文件的最后一行看到。第一个构造的对象现在包含来自第二个对象的数据,而不是它最初包含的值。

任何关于我做错了什么和/或如何追查此类问题的建议将不胜感激。

ANBNote.h

@interface ANBNote : NSObject
@property (nonatomic,readwrite) NSArray* references;
- (id)initWithJsonNSDictionary*)data;
@end

ANBNote.m

#import "ANBNote.h"

@implementation ANBNote
NSArray * _references;

-(id) init {
  if(!(self=[super init])) return nil;
  _references=@[];
  return self;
}

-(id)initWithJsonNSDictionary *)jsonObject {      
  if(!(self = [self init] ) ) { return nil; }    
  _references = jsonObject[@"references"];    
  return self;
}

-(void) setReferencesNSArray *)references {
  _references = references;
}

-(NSArray *)references {
  return _references;
}    

@end

Test.m

...
NSDictionary * d1 = @{@"references"[@"r1",@"r2"]};
NSDictionary * d2 = @{@"references"[@"q1",@"q2"]};

ANBNote * n1 = [[ANBNote alloc] initWithJson:d1];
NSLog(@"R1 = %p, %@", n1.references, n1.references); // Prints r1, r2 - as expected

ANBNote * n2 = [[ANBNote alloc] initWithJson:d2];
NSLog(@"R2 = %p, %@", n2.references, n2.references); // Prints q1, q2 - as expected
NSLog(@"R1 = %p, %@", n1.references, n1.references); // Prints q1, q2 - Oh No!

请注意,如果我删除自定义引用属性函数并依赖编译器生成的版本,一切似乎都正常运行。



Best Answer-推荐答案


这不是 ivar:

@implementation ANBNote
NSArray * _references;

这是一个全局性的。您的类的所有实例只有一个,而不是每个实例一个。当下一个实例设置它时,前面的实例会看到新值,因为它是同一个变量。您需要将其放入花括号中以使其成为 ivar:

@implementation ANBNote
{
    NSArray * _references;
}

不过,无需显式声明变量——您仍然可以自己实现访问器,并让编译器创建 ivar,只要您使用默认的合成名称(下划线 + 属性名称)。

关于ios - 为什么我的对象会发生意外变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18285624/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4