在我的 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 代码中为 NSIndexPath
的 subRow
设置了一个值,当该 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/