我有一个非常基本的示例,我正在从 JSON 将一些数据读入一个类,并且我的对象正在以某种方式损坏。我怀疑我遗漏了一些关于属性/ARC 是如何工作的细节,但我不确定它是什么,或者我将如何追踪它。
我已经减少了我的原始代码,所以问题很明显。然而,这意味着不清楚我为什么要使用自定义属性等 - 我的真实代码在那里有更多功能......
该问题可以在 Test.m 文件的最后一行中看到。第一个构造的对象现在包含来自第二个对象的数据,而不是它最初包含的值。
任何关于我做错了什么和/或如何追踪此类问题的建议将不胜感激。
ANBNote.h
@interface ANBNote : NSObject
@property (nonatomic,readwrite) NSArray* references;
- (id)initWithJson:(NSDictionary*)data;
@end
ANBNote.m
#import "ANBNote.h"
@implementation ANBNote
NSArray * _references;
-(id) init {
if(!(self=[super init])) return nil;
_references=@[];
return self;
}
-(id)initWithJson:(NSDictionary *)jsonObject {
if(!(self = [self init] ) ) { return nil; }
_references = jsonObject[@"references"];
return self;
}
-(void) setReferences:(NSArray *)references {
_references = references;
}
-(NSArray *)references {
return _references;
}
@end
测试.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!
请注意,如果我删除自定义引用属性函数并依赖编译器生成的版本,一切似乎都正常。