【问题标题】:Avoid repetitive code in Objective C避免 Objective C 中的重复代码
【发布时间】:2014-09-04 01:42:13
【问题描述】:

我在 C++ 类中有两个非常相似的方法。唯一的区别是内部调用的 Objective-C 方法:

void MyClass::loadFromImage(UIImage *image)
{
    // ... Prepare dictionary and error

    GLKTextureInfo* info = [GLKTextureLoader textureWithCGImage:image.CGImage options:options error:&err];

    // ... Use GLKTexureInfo to load a texture
}

void Surface::loadFromImage(const char* imageName)
{
    // ... Prepare dictionary and error

    GLKTextureInfo* info = [GLKTextureLoader textureWithContentsOfFile:path options:options error:&err];

    // ... Use GLKTexureInfo to load a texture
}

如何结合这两种方法来减少冗余代码?

我希望做一些类似于this thread 的事情,但不确定语法在Objective-C 中应该如何工作。谢谢你的帮助!

【问题讨论】:

  • Objective-c 没有泛型。您无法实现他们在该线程中的建议。

标签: c++ objective-c refactoring


【解决方案1】:

替换

// ... 准备字典和错误

// ... 使用 GLKTexureInfo 加载纹理

使用loadFromImage 的两个版本都可以使用的方法。

是的代码重用!

【讨论】:

    最近更新 更多