问题描述
我有一个非常基本的示例,其中我从JSON读取一些数据到类中,并且我的对象以某种方式被损坏.我怀疑我缺少有关properties/ARC如何工作的详细信息,但是我不确定它是什么,或者如何跟踪它.
I've got a very basic example where I'm reading some data into a class from JSON, and my objects are getting corrupted somehow. I suspect I'm missing some detail about how properties/ARC is working, but I'm not sure what it is, or how I'd track it down.
我已经减少了原始代码,以便使问题显而易见.但这意味着尚不清楚为什么要使用自定义属性等.-我的真实代码在其中具有更多功能...
I've reduced my original code so that the problem is obvious. However this means that its not clear why I'm using custom properties etc. - my real code has more functionality in there...
该问题可以在Test.m文件的最后一行中看到.现在,第一个构造的对象包含第二个对象的数据,而不是它最初包含的值.
The issue can be seen in the last line of the Test.m file. The first constructed object now contains data from the second object rather than the value it originally contained.
对于我在做什么和/或如何查找此类问题的任何建议,将不胜感激.
Any advice on what I'm doing wrong and/or how to track down this kind of issue would be greatly appreciated.
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
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!
请注意,如果我删除自定义引用属性函数并依靠编译器生成的版本,则一切似乎都正常运行.
Note that if I remove custom references property functions and rely on the compiler generated version everything seems to behave correctly.
推荐答案
这不是ivar:
@implementation ANBNote
NSArray * _references;
这是全球性的.对于您的类的所有实例,只有一个,而对于每个实例,则没有一个.当下一个实例对其进行设置时,先前的实例将看到新值,因为它是相同的变量.您需要将其放在花括号中以使其成为ivar:
it's a global. There's only one for all the instances of your class, not one for each. When the next instance sets it, the previous instances see the new values because it's the same variable. You need to put it into curly braces to make it an ivar:
@implementation ANBNote
{
NSArray * _references;
}
不过,无需显式声明变量-您仍然可以自己实现访问器,并让编译器创建ivar,只要您使用默认的综合名(下划线+属性名)即可.
There's no need to declare the variable explicitly, though -- you can still implement accessors yourself and let the compiler create the ivar as long as you use the default synthesized name (underscore + property name).
这篇关于为什么我的对象发生意外变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!