ios - 在 Swift 3 的值类型中访问 Objective-C 类别的属性(相关引用)

标签 ios objective-c swift associated-object objc-bridging-header

在我的 Objective-C 类的 .h 文件中,我为 NSIndexPath 创建了一个类别,如下所示:

@interface NSIndexPath (YVTableView)

@property (nonatomic, assign) NSInteger subRow;

@end

并且在该类的 .m 文件中,我已经实现了:

static void *SubRowObjectKey;

@implementation NSIndexPath (YVTableView)

@dynamic subRow;

- (NSInteger)subRow
{
    id subRowObj = objc_getAssociatedObject(self, SubRowObjectKey);
    return [subRowObj integerValue];
}

- (void)setSubRow:(NSInteger)subRow
{
    id subRowObj = [NSNumber numberWithInteger:subRow];
    objc_setAssociatedObject(self, SubRowObjectKey, subRowObj, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

现在,当我使用 IndexPath 在 Swift 3 中访问 NSIndexPath 的 subRow 属性时,它给我错误:

Value of type 'IndexPath' has no member 'subRow'

如果我尝试使用类型转换访问它

let subIndexPath = indexPath as NSIndexPath
let subRowIndex = subIndexPath.subRow

它总是返回“0”作为“subRow”值。可能是因为 IndexPath 是值类型,NSIndexPath 是引用类型。

我已经使用 Objective-C 将 UITableViewDelegate 实现到我的自定义委托(delegate)并将其实现到 Swift 类,但是在我实现自定义委托(delegate)方法的 Swift 中,我遇到了这个问题。

我还尝试在我的自定义委托(delegate)实现(Swift 代码)中使用 NSIndexPath 而不是 IndexPath,但它给我错误“Type YVViewController does not conform to protocol, Candidate has non matching-type”。

这是我的自定义委托(delegate)声明:

@protocol YVTableViewDelegate <UITableViewDelegate>

@required

- (UITableViewCell *)tableView:(SKSTableView *)tableView cellForSubRowAtIndexPath:(NSIndexPath *)indexPath;

@end

它在 Swift 2.x 上工作得很好,但在迁移到 Swift 3 后,我遇到了这个问题。

最佳答案

NSIndexPath 关联的 subRow 不会与从该 NSIndexPath 转换的 IndexPath 关联,因为它们不是同一个“对象”。 IndexPath 是 Swift 中的值类型,使用 struct 关键字定义,因此它不能有 Objective-C 关联对象。

因此,即使您在 Objective-C 代码中为 NSIndexPathsubRow 设置了一个值,当该 NSIndexPath 时该值也会丢失被转换为 Swift 的 IndexPath。这就是为什么当您再次将 IndexPath 转换回 NSIndexPath 时,subRow 值始终为 0,这是默认值。

在您的情况下,您需要在 Swift 中声明协议(protocol)并将索引路径参数类型指定为 NSIndexPath

func tableView(_ tableView: SKSTableView, cellForSubRowAt indexPath: NSIndexPath) -> UITableViewCell

关于ios - 在 Swift 3 的值类型中访问 Objective-C 类别的属性(相关引用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39997473/

相关文章:

ios - UIKeyboardDidShowNotification 在两个 ViewController 中调用

iphone - 图像没有移回正确的位置

ios - ios导航栏和 subview 之间的差距?

ios - 从电话簿 iOS Swift 获取电子邮件联系人

iOS 和 mPOS 终端 - 非接触式支付

ios - main.async 中的 block 仅在 global.async block 完成后执行

添加 map View 时 iphone 应用程序崩溃

ios - 在 objective-c 中更改应用程序扩展的屏幕旋转

ios - XCode 7 上不显示 UIImageView 网络图像

ios - 如何减少 collectionview 中两个单元格之间的垂直空间?