• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 为什么我的对象会发生意外变化?

[复制链接]
菜鸟教程小白 发表于 2022-12-13 03:32:43 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我有一个非常基本的示例,我正在将一些数据从 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap