【问题标题】:Cross-platform NSValue category跨平台 NSValue 类别
【发布时间】:2014-05-28 11:38:10
【问题描述】:

我正在尝试为 Cocoa 和 iOS 创建一个跨平台的 NSValue 类别,它将处理 CGPoint/NSPoint 和 CGSize/NSSize 等。

我有这个:

#ifdef __MAC_OS_X_VERSION_MAX_ALLOWED
// Mac OSX

+ (NSValue *) storePoint:(NSPoint)point {
  return [NSValue valueWithPoint:point];
}

+ (NSPoint) getPoint {
  return (NSPoint)[self pointValue];
}


#else
// iOS

+ (NSValue *) storePoint:(CGPoint)point {
  return [NSValue valueWithCGPoint:point];
}

+ (CGPoint) getPoint {
  return (CGPoint)[self CGPointValue];
}


#endif

Mac 部分运行良好,但 iOS 部分给我一个错误

  return (CGPoint)[self CGPointValue];

有两条消息:1)没有已知的选择器 CGPointValue 的类方法和“使用类型 CGPoint(又名 struct CGPoint),其中需要算术或指针类型。

这是为什么呢?

【问题讨论】:

标签: ios cocoa cgpoint cgsize nsvalue


【解决方案1】:

因为+[NSValue CGPointValue]不存在你想要-[NSValue CGPointValue]

#ifdef __MAC_OS_X_VERSION_MAX_ALLOWED
// Mac OSX

+ (NSValue *) storePoint:(NSPoint)point {
  return [NSValue valueWithPoint:point];
}

- (NSPoint) getPoint { // this should be instance method
  return (NSPoint)[self pointValue];
}


#else
// iOS

+ (NSValue *) storePoint:(CGPoint)point {
  return [NSValue valueWithCGPoint:point];
}

- (CGPoint) getPoint { // this should be instance method
  return (CGPoint)[self CGPointValue];
}


#endif

【讨论】:

  • 啊,好吧,但是出于好奇,为什么 Xcode 在我为 Cocoa 编译时没有给我任何错误?
  • @RubberDuck 我不知道...也许 Xcode 认为 selfid (无类型)所以没有进行类型检查
【解决方案2】:

为了让事情更简单,只需创建一个仅适用于 iOS 的类别并使用与 OS X 上相同的方法名称,因为对于 OS X CGPoint 和 NSPoints 是相同的,你不需要更多,而且你不需要'不必修改您的 OS X 代码。

@implementation NSValue (XCross)
#if TARGET_OS_IPHONE
+ (NSValue *) valueWithPoint:(CGPoint)point {
    return [NSValue valueWithCGPoint:point];
}

- (CGPoint) pointValue {
    return [self CGPointValue];
}
#endif
@end

【讨论】:

    【解决方案3】:
    + (CGPoint) getPoint {
      return (CGPoint)[self CGPointValue];
    }
    

    您的变量以 maj 开头?用 min 设置变量不是更好吗?可能是 CGPoint 类的问题。

    [self cgPointValue];
    

    【讨论】:

    • 没有。这个is a Cocoa method。您不能只更改名称。问题是它是一个实例方法,而不是一个类方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 2019-05-15
    • 2019-12-28
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多