更改数组中一个对象的值正在更改数组中的所有对象

时间:2017-05-05 14:49:33

标签: objective-c arrays get set

当我在Objective-C中覆盖get set时,如果此对象在数组中,如果我更改了其中一个覆盖属性,则数组中的所有对象都已更改

我有一个名为“人”的课程:

#import <Foundation/Foundation.h>

@interface Person : NSObject
@property(nonatomic,copy) NSString *Name;
@property(nonatomic,copy) NSDecimalNumber* Money;

-(instancetype)initWithName:(NSString*)name andMoney:(NSDecimalNumber*)money;
@end

在“Person.m”中,我覆盖了“money”属性的get / set方法:

   #import "Person.h"
    @implementation Person

    NSDecimalNumber* _Money;

    -(instancetype)initWithName:(NSString*)name andMoney:(NSDecimalNumber*)money{
        self = [super init];
        if(self){
            _Name = name;
            _Money = money;
        }
        return self;
    }

    -(NSDecimalNumber *)Money{
        return _Money;
    }

    -(void)setMoney:(NSDecimalNumber *)Money{
        _Money = Money;
    }

    @end

现在,我和一些人有一个阵列:

NSMutableArray<Person*> *personArray = [[NSMutableArray alloc]init];

[personArray addObject:[[Person alloc]initWithName:@"11" andMoney:[NSDecimalNumber decimalNumberWithString:@"0.1"]]];
[personArray addObject:[[Person alloc]initWithName:@"22" andMoney:[NSDecimalNumber decimalNumberWithString:@"0.2"]]];
[personArray addObject:[[Person alloc]initWithName:@"33" andMoney:[NSDecimalNumber decimalNumberWithString:@"0.3"]]];
[personArray addObject:[[Person alloc]initWithName:@"44" andMoney:[NSDecimalNumber decimalNumberWithString:@"0.4"]]];
[personArray addObject:[[Person alloc]initWithName:@"55" andMoney:[NSDecimalNumber decimalNumberWithString:@"0.5"]]];
[personArray addObject:[[Person alloc]initWithName:@"66" andMoney:[NSDecimalNumber decimalNumberWithString:@"0.6"]]];
[personArray addObject:[[Person alloc]initWithName:@"77" andMoney:[NSDecimalNumber decimalNumberWithString:@"0.7"]]];
[personArray addObject:[[Person alloc]initWithName:@"88" andMoney:[NSDecimalNumber decimalNumberWithString:@"0.8"]]];

现在,我改变了一个人的钱和名字财产:

[[personArray objectAtIndex:5]setMoney:[NSDecimalNumber decimalNumberWithString:@"0.22"]];

[[personArray objectAtIndex:5]setName:@"terry"];

现在,阵列的所有人的钱财已经改变了!!

for (Man* man in personArray) {
    NSLog(@"%@--%@",man.Name,man.Money);
}

阵列中金钱财产价值的每个人都是“0.22”!!

为什么?

1 个答案:

答案 0 :(得分:1)

问题是您的NSDecimalNumber* _Money;声明不是实例变量。它是一个文件全局变量。由于只有一个这样的变量,因此它的值用于Person类的所有实例。所以它显示了最后设定的值。

您需要将声明放在@implementation块中,如下所示:

@implementation Person {
    NSDecimalNumber* _Money;
}

// and the rest of your code

@end

FYI - 变量名称应以小写字母开头:

NSDecimalNumber* _money;

班级名称以大写字母开头。