父类中有个静态变量,子类会自动继承:
注意:通过对象对象方法和通过类方法修改static静态变量的结果是不一样的。
通过类(+方法)方法对static变量进行修改:父类和子类都会对彼此的静态变量进行修改。
通过对象(-方法)方法对static变量进行修改:只能修改本类中对象方法中获取的静态变量。
在对象(-方法)方法中修改了静态变量的值,通过类方法获取静态变量的值,得到的始终是父类中静态变量的值。
//父类Person
static NSString *_st = @"11";
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSHashTable *family;
- (void)test;
+ (void)setSt:(NSString *)st;
+ (NSString *)st;
@end
- (void)test {
NSLog(@"Person1:%@",_st);
_st = @"Person";
NSLog(@"Person2:%@",_st);
}
+ (void)setSt:(NSString *)st {
_st = [st copy];
}
+ (NSString *)st {
return _st;
}
//子类
@interface Son : Person
@end
@implementation Son
- (void)test {
NSLog(@"Son1:%@",_st);
_st = @"Son";
NSLog(@"Son2:%@",_st);
}
@end
int main()
{
Person *peron = [[Person alloc] init];
Son *son = [[Son alloc] init];
[peron test];
[son test];
[Person setSt:@"person class"];
NSLog(@"person class===");
[peron test];
[son test];
NSLog(@"Person class ===");
[Son setSt:@"Son class"];
[peron test];
[son test];
NSLog(@"get class ====");
NSLog(@"Person class:%@",[Person st]);
NSLog(@"Son class:%@",[Son st]);
}
//打印结果
2018-05-10 14:08:36.228924+0800 TestOC[2183:485436] Person1:11
2018-05-10 14:08:36.228946+0800 TestOC[2183:485436] Person2:Person
2018-05-10 14:08:36.228956+0800 TestOC[2183:485436] Son1:11
2018-05-10 14:08:36.228964+0800 TestOC[2183:485436] Son2:Son
2018-05-10 14:08:36.228977+0800 TestOC[2183:485436] person class==========
2018-05-10 14:08:36.228985+0800 TestOC[2183:485436] Person1:person class
2018-05-10 14:08:36.228992+0800 TestOC[2183:485436] Person2:Person
2018-05-10 14:08:36.229000+0800 TestOC[2183:485436] Son1:Son
2018-05-10 14:08:36.229007+0800 TestOC[2183:485436] Son2:Son
2018-05-10 14:08:36.229014+0800 TestOC[2183:485436] Person class ======
2018-05-10 14:08:36.229022+0800 TestOC[2183:485436] Person1:Son class
2018-05-10 14:08:36.229029+0800 TestOC[2183:485436] Person2:Person
2018-05-10 14:08:36.229037+0800 TestOC[2183:485436] Son1:Son
2018-05-10 14:08:36.229044+0800 TestOC[2183:485436] Son2:Son
2018-05-10 14:08:36.229052+0800 TestOC[2183:485436] get class ====
2018-05-10 14:08:36.229061+0800 TestOC[2183:485436] Person class:Person
2018-05-10 14:08:36.229206+0800 TestOC[2183:485436] Son class:Person
网友评论