2019独角兽企业重金招聘Python工程师标准>>>
属性在.h文件中和在.m中声明是有区别的。区别就是,在.h文件中声明的属性,外部类可以通过“类实例.属性”来调用,但在.m中声明的则不可以,获取和设置的方法,只能是通过setValue:forKey和valueForKey来实现。 成员变量,有三种权限,就是大家都知道的@private、@protected、@public ,写在.m文件中时,相当于是@private权限,子类无法访问,验证了一下,做权限修改也无效。而写在.h文件中,默认是@protected权限,子类可以访问,可以做权限修改。
@interface部分为类扩展(extension)。在.m文件中
#import
"LCCertificationInformationViewController.h"
// 这就是类扩展
@interface
LCCertificationInformationViewController
()
@property
(
nonatomic
,
strong
)
UITableView
*tableView;
@end
@implementation
LCCertificationInformationViewController
- (void)viewDidLoad {
}
其被设计出来就是为了解决两个问题的,其一,定义类私有方法的地方。其二,实现public readonly,private readwrite的property(意思是在h头文件中定义一个属性对外是readonly的,但在类的内部希望是可读写的,所以可以在m源文件中的@interface部分重新定义此属性为readwrite,此时此属性对外是只读的,对内是读写的)。
类里面还有很多组@interface 和@implementation,这么做用意何在?
举例:类名为:SalesProject
.h文件中包含
@interface
SalesProject :
NSObject
<
JsonAndObjectTransformProtocol
>
@interface SalesProjectPrimaryInfo : NSObject <
JsonAndObjectTransformProtocol>
@interface
SalesProjectStatus :
NSObject
.m文件包含
@implementation SalesProject :
NSObject <
JsonAndObjectTransformProtocol>
@implementation
SalesProjectPrimaryInfo :
NSObject
<
JsonAndObjectTransformProtocol
>
@implementation
SalesProjectStatus :
NSObject
类名与文件名.h.m同名是一般的开发习惯,但不是必须的。多个类也可以写在同一对.h.m文件里的。
没什么实际意义,可能就是不想再多开几个文件了吧。或者这三个类的关系比较密切,就写在一起了。。。
#import
<UIKit/UIKit.h>
@interface
ViewController1 :
UIViewController
@property
(
nonatomic
,
copy
,
readonly
)
NSString
*readOnlyStr;
@end
#import
"ViewController1.h"
@interface
ViewController1
()
//@property (nonatomic, copy,
readwrite
) NSString *readOnlyStr;// 这里去掉注释下面就不会报错
@end
@implementation
ViewController1
- (
void
)viewDidLoad {
[super viewDidLoad];
self
.readonlyStr =
@"readonlyStr
”
;// 报错
}
此外,也可在此.m部分声明变量和属性,但声明的变量,属性和方法均为私有的,只能够被当前类访问,相当于private。
.h
@interface
ViewController1
()
{
NSString *string; // pirvate 的只能在当前类使用 ;assign 引用计数不加 1 。
}
{
NSString *string; // pirvate 的只能在当前类使用 ;assign 引用计数不加 1 。
}
@property
(
nonatomic
,
retain
)
NSString
*string2;
// pirvate
的只能在当前类使用
;retain
引用计数加
1
。
.m
NSString
*s = [
NSString
stringWithFormat
:
@"string"
];
NSString
*s2 = [
NSString
stringWithFormat
:
@"string2"];
string = s;
self
.
string2 = s2;
NSLog
(
@"string
引用计数
:%lu;string2
引用计数
:%lu"
,
string
.
retainCount
,
self
.
string2
.
retainCount
);
//string
引用计数
:1;string2
引用计数
:2
NSString
*strings =
string;
NSString
*string2s =
self
.
string2;
NSLog
(
@"string
引用计数
:%lu;strings
引用计数
:%lu"
,
string
.
retainCount
,strings.
retainCount
);
//string
引用计数
:1;strings
引用计数
:1
NSLog
(
@"string2
引用计数
:%lu;string2s
引用计数
:%lu"
,
self
.
string2
.
retainCount
,string2s.
retainCount
);
//string2
引用计数
:2;string2s
引用计数
:2