我有一个 UITableViewCell ProductsCell
,我在 nib 中注册了它,然后出队使用它。
我想将它的属性设置为只读。如何做得更好?
代码如下:
@property (nonatomic, strong, readonly) MyProductsVC * targetMyProductsVC;
- (MyProductsVC *)targetMyProductsVC{
if(!_targetMyProductsVC){
UIResponder *target = self.nextResponder;
do {
target = target.nextResponder;
} while (![target isKindOfClass: ZBMyProductsVC.self] && target != nil);
_targetMyProductsVC = (ZBMyProductsVC *)target;
}
return _targetMyProductsVC;
}
我无法执行。在 -init
,-awakeFromNib
中,因为我使用 UIResponder
找到父 ViewController。
因为在上面的方法中,单元格似乎还没有添加到 super View 上。
如果我这样做,
@property (nonatomic, strong, readonly) MyProductsVC * targetMyProductsVC;
Xcode 报告:
Use of undeclared identifier '_targetMyProductsVC'
设置两个属性即可。一个像上面一样在里面,只需在 getter
方法之外设置另一个只读属性(return
前一个属性。)
有点脏,
有更好的方法吗?
代码可以工作:
@property (nonatomic, strong, readonly) MyProductsVC * targetMyProductsVCReadOnly;
@property (nonatomic, strong) MyProductsVC * targetMyProductsVC;
- (MyProductsVC *)targetMyProductsVC{
if(!_targetMyProductsVC){
UIResponder *target = self.nextResponder;
do {
target = target.nextResponder;
} while (![target isKindOfClass: ZBMyProductsVC.self] && target != nil);
_targetMyProductsVC = (ZBMyProductsVC *)target;
}
return _targetMyProductsVC; }
- (MyProductsVC *)targetMyProductsVCReadOnly{
return self.targetMyProductsVC; }
最佳答案
因为您正在为 readonly
属性实现自己的属性 getter,这意味着只有一个访问器(即没有 setter),编译器不会自动声明支持变量。来自 Encapsulating Data :
Note: The compiler will automatically synthesize an instance variable in all situations where it’s also synthesizing at least one accessor method. If you implement both a getter and a setter for a
readwrite
property, or a getter for areadonly
property, the compiler will assume that you are taking control over the property implementation and won’t synthesize an instance variable automatically.If you still need an instance variable, you’ll need to request that one be synthesized:
@synthesize property = _property;
您在 getter 实现之前插入以上内容以解决未声明的变量错误。
HTH
关于ios - 如何以只读方式设置 UICollectionViewCell 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48063163/