自定义readonly属性的用法

时间:2023-03-09 14:38:01
自定义readonly属性的用法

具有readonly特性的属性,相当于仅对外提供一个读取接口,在实现文件中是不会自动生成对应的成员变量的,因此使用方法为:

// MyItem.h
@interface MyItem : NSObject
@property (nonatomic, strong, readonly) NSString *string;
@end
// MyItem.m

@interface MyItem ()
{
NSString *_string;
}
@end @implement MyItem - (id)init
{
self = [super init];
if (self)
{
_string = [[NSString alloc] init];
}
return self;
} - (NSString*)string
{
return _string;
} @end