KVC(3) 访问集合属性

2020-01-23  本文已影响0人  yxibng

访问集合属性

普通方式访问

valueForKey:
setValue:forKey:

可变代理方式

mutableArrayValueForKey:
mutableArrayValueForKeyPath:
 
mutableSetValueForKey:
mutableSetValueForKeyPath:
 
mutableOrderedSetValueForKey:
mutableOrderedSetValueForKeyPath:

Account

@interface Account : NSObject

@property (nonatomic, copy) NSString *bankName;
@property (nonatomic, assign) NSInteger money;

@end

Person

@interface Person : NSObject

@property (nonatomic, strong) NSArray *accounts;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end

ViewController

@interface ViewController ()

@property (nonatomic, strong) Person *person;

@end


- (void)viewDidLoad {
    [super viewDidLoad];
    
    _person = [[Person alloc] init];
    _person.name = @"张三";
    _person.age = 10;
    
    Account *account_1 = [[Account alloc] init];
    account_1.bankName = @"中国银行";
    account_1.money = 100;
    
    Account *account_2 = [[Account alloc] init];
    account_2.bankName = @"交通银行";
    account_2.money = 200;
    _person.accounts = @[account_1, account_2];
    
    
    // Do any additional setup after loading the view.
}

- (IBAction)newAccount:(id)sender {
    
    NSMutableArray *accounts = [self.person mutableArrayValueForKey:@"accounts"];
    
    Account *account_1 = accounts.firstObject;
    account_1.money = 999;
    
    Account *account_3 = [[Account alloc] init];
    account_3.bankName = @"建设银行";
    account_3.money = 500;
    
    [accounts addObject:account_3];
    
    for (Account *account  in self.person.accounts) {

        NSLog(@"name = %@, money = %ld", account.bankName, (long)account.money);
    }
    
}

上一篇 下一篇

猜你喜欢

热点阅读