1

在我的 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

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

“IndexPath”类型的值没有成员“subRow”

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

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

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

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

我还尝试在我的自定义委托实现(Swift 代码)中使用 NSIndexPath 而不是 IndexPath,但它给了我错误“Type YVViewController 不符合协议,Candidate has non matching-type”。

这是我的自定义代表声明:

@protocol YVTableViewDelegate <UITableViewDelegate>

@required

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

@end

它在 Swift 2.x 上运行得非常好,但是在迁移到 Swift 3 之后,我遇到了这个问题。

4

2 回答 2

1

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

因此,即使您在 Objective-C 代码中设置了 a 的值,当它subRow被转换为 Swift 的. 这就是为什么当您再次将back 转换为 时,该值始终为 0,这是默认值。NSIndexPathNSIndexPathIndexPathIndexPathNSIndexPathsubRow

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

func tableView(_ tableView: SKSTableView, cellForSubRowAt indexPath: NSIndexPath) -> UITableViewCell
于 2016-10-13T17:18:10.090 回答
1

但是,您可以按如下方式更新您的类别:-

- (NSInteger)subRow
{

    id myclass = [SKSTableView class];
  //  id subRowObj = objc_getAssociatedObject(self, SubRowObjectKey);
    id subRowObj = objc_getAssociatedObject(myclass, SubRowObjectKey);
    return [subRowObj integerValue];
}

- (void)setSubRow:(NSInteger)subRow
{
    id subRowObj = [NSNumber numberWithInteger:subRow];

    id myclass = [SKSTableView class];
   // objc_setAssociatedObject(self, SubRowObjectKey, subRowObj, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(myclass, SubRowObjectKey, subRowObj, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
于 2017-06-21T09:38:33.870 回答