ios - 设置只读属性值

标签 ios objective-c iphone

<分区>

我有一个只读属性

@property (nonatomic, readonly)  NSInteger   keepalive;

使用getter方法

-(NSInteger)keepalive
{
    return _keepalive / 1000;
}

错误 - 使用未声明的标识符

并尝试在 init 方法中设置一个值

- (instancetype)init
{
    self = [super init];

    if (self)
    {
        _keepalive = 25000;
    }
    return self;
}

错误 - 使用未声明的标识符

无法理解使用 getter 拥有只读属性的原因和正确方法。

编辑: 我不想按照评论中的建议添加 synthesize,因为它不再需要了 - as stated here我在下面得到了正确答案。 谢谢安德烈·斯洛塔!

最佳答案

在您的情况下,您可以在实现文件中将该属性重新声明为读写:

.h:

@property (nonatomic, readonly)  NSInteger keepalive;

.m:

@property (nonatomic, readwrite)  NSInteger keepalive;

这让您可以在您的实现中使用编译器生成的原子 setter 和 getter,但不会将 setter 暴露给世界其他地方。

(参见 https://www.bignerdranch.com/blog/property-values/)

关于ios - 设置只读属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36572797/

相关文章:

ios - 我如何避免由于防止变量为@(null)而导致崩溃?

ios - SwiftUI - 数据源为空时动态列表过滤动画飞到右侧

objective-c - (null) 和 <null> 之间有什么区别?

iPhone SDK - 突出显示 TableView 中选定的单元格

ios - 从 PLCrashReport 获取完整数据

ios - 在 WatchKit 中更新表格行

Ios - 如何在不同的 View Controller 中启动计时器

ios - 可达性转到 "Wi-Fi Settings"按钮不起作用

iphone - 用于接近检测 iOS 的蓝牙 LE RSSI

ios - didMoveToParentViewController 和 willMoveToParentViewController