gpt4 book ai didi

objective-c - Objective C - 在属性上声明可选字段

转载 作者:行者123 更新时间:2023-12-05 01:53:58 25 4
gpt4 key购买 nike

在 objective-c 中是否可以将 Bool 和 float 类型设置为 Optional 我找不到任何解决方法?

 @property (nonatomic, assign) float percentageOfCases;
@property (nonatomic, assign) float inspectionPercentageOfCases;
@property (nonatomic, assign) NSString<Optional> *inspectionStatus;
@property (nonatomic, assign) BOOL sendNotification;

最佳答案

swift 的 Optional对应于Objective-C中的可空性,而在Objective-C中,只有指针类型可以为空。所以你必须将你的属性更改为指针类型,在本例中这意味着 NSNumber *对于 float属性和 NSNumber *CFBooleanRef对于 BOOL属性(property)。

但是,更改类型将使 Swift 将属性导入为 NSNumberCFBoolean而不是 FloatBool .所以你可能还想申请 NS_REFINED_FOR_SWIFT每个属性,以及一个 Swift extension定义 Float 类型的属性和 Bool .这是它的样子:

// In your Objective-C header:

@interface MyObject : NSObject
@property (nonatomic, assign, nullable) NSNumber *percentageOfCases NS_REFINED_FOR_SWIFT;
@property (nonatomic, assign, nullable) NSNumber *inspectionPercentageOfCases NS_REFINED_FOR_SWIFT;
@property (nonatomic, assign, nullable) NSString *inspectionStatus;
@property (nonatomic, assign, nullable) CFBooleanRef sendNotification NS_REFINED_FOR_SWIFT;
@end
extension MyObject {
var percentageOfCases: Float? {
get { __percentageOfCases?.floatValue }
set { __percentageOfCases = newValue as NSNumber? }
}

var inspectionPercentageOfCases: Float? {
get { __inspectionPercentageOfCases?.floatValue }
set { __inspectionPercentageOfCases = newValue as NSNumber? }
}

var sendNotification: Bool? {
get { (__sendNotification as NSNumber?)?.boolValue }
set { __sendNotification = newValue as NSNumber? }
}
}

请注意,Xcode 不会为双下划线标识符(如 __percentageOfCases )提供代码完成。

关于objective-c - Objective C - 在属性上声明可选字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70887057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com