iOS中.m文件中声明的属性是私有的,但是不是绝对私有的。私有属性通过KVC可以设置和获得该属性的。而私有是相对于封装后他人不知道你的私有属性的情况下的私有。例子如图:
Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
- (NSString *)getName;
- (NSInteger)getAge;
@end
#import "Person.h"
@interface Person()
{
@private
NSString *_name;
}
@property (nonatomic,assign) NSInteger age;
@end
@implementation Person
- (NSString *)getName
{
return _name;
}
- (NSInteger)getAge
{
return _age;
}
@end
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Person *person = [[Person alloc]init];
[person setValue:@"merry" forKey:@"name"];
NSLog(@"KVC获取的人名:%@",[person valueForKey:@"name"]);
NSLog(@"方法获取的人名:%@",[person getName]);
[person setValue:@24 forKey:@"age"];
NSLog(@"KVC获取的年纪:%@",[person valueForKey:@"age"]);
NSLog(@"方法获取的年纪:%ld",[person getAge]);
}
@end
运行结果为: