访问集合属性
普通方式访问
valueForKey:
setValue:forKey:
可变代理方式
mutableArrayValueForKey:
mutableArrayValueForKeyPath:
mutableSetValueForKey:
mutableSetValueForKeyPath:
mutableOrderedSetValueForKey:
mutableOrderedSetValueForKeyPath:
- 当你修改代理对象的时候,添加,删除,替换里面的内容,对应的集合属性的内容也会跟着修改。
- 当试图修改一个非可变集合的内容的时候,效率会特别高
- 正常的修改非可变集合的方式为
-
valueForKey:
得到non-mutable
集合(如 NSArray *array) - 根据这个非可变集合(array),创建一个
mutalbe
集合(NSMutableArray *mArray) - 修改这个
mArray
- 通过
setValue:forKey:
将修改后的集合重新赋值
-
- 可变代理方式
-
mutableArrayValueForKey:
得到mutalbe
代理(NSMutableArray *mArray) - 修改这个
mArray
- 对代理对象的修改自动反馈到对应的属性上面
-
- 正常的修改非可变集合的方式为
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);
}
}
网友评论