gpt4 book ai didi

ios - 将 Objective-C 动态绑定(bind)转换为 swift 2

转载 作者:行者123 更新时间:2023-11-30 13:15:26 24 4
gpt4 key购买 nike

我遇到了一种情况,我正在将 obj-c 项目转换为 swift。如下

    // few lazy property initializers as, 
@property (nonatomic, strong) MyObject *property1;
@property (nonatomic, strong) MyObject *property2;
@property (nonatomic, strong) MyObject *property3;
...

// I keep an index value to map these into a dictionary for reference
- (NSDictionary *)indexMap
{
if (!_indexMap)
{
_indexMap = @{
@(index1) : [NSValue valueWithPointer:@selector(property1)],
@(index2) : [NSValue valueWithPointer:@selector(property2)],
...
};
}
return _indexMap;
}

// other dictionary for index to class map
- (NSDictionary *)classMap
{
return @{

NSStringFromClass(@"MyClassA") : @(index1),
NSStringFromClass(@"MyClassB") : @(index1),
NSStringFromClass(@"MyClassC") : @(index1),

NSStringFromClass(@"MyClassD") : @(index2),
NSStringFromClass(@"MyClassE") : @(index2),

NSStringFromClass(@"MyClassF") : @(index3),
...
};
}

// finally i have method to pass in the class name & it will first find corresponding index, then use the index to return the property selector.

我关心的是这样做的快速方式是什么?

最佳答案

实现此目的的一种方法是保留执行初始化的回调列表。这是一种非常灵活的解决方案,尽管当然可以使用更简单的替代方案:

class ComponentManager {

// Global singleton: ComponentManager.sharedManager
static let sharedManager = ComponentManager()

// Define a callback type which is used to create instances.
// This is the lazy initialiser.
typealias Constructor = () -> NSObject?

private var constructor = [String: Constructor]()
private var instances = [String: NSObject]()

func register(name: String, constructor: Constructor) {
self.constructor[name] = constructor
}

func instanceNamed(name: String) -> NSObject? {

if let instance = instances[name] {
return instance
}

guard let constructor = constructor[name] else {
return nil
}

guard let instance = constructor() else {
return nil
}

instances[name] = instance

return instance
}
}

使用它:

class A: NSObject {
let foo: String
init(foo: String) {
self.foo = foo
}
}

class B: NSObject {
let bar: Int
init(bar: Int) {
self.bar = bar
}
}

let manager = ComponentManager.sharedManager

// Register our classes.
// Note the callback functions which actually perform the
// initialisation, these are only called when the class is requested the
// first time.
manager.register("A") { return A(foo: "fizz") }
manager.register("B") { return B(bar: 47) }

// Create some instances
let a = manager.instanceNamed("A") as? A
let b = manager.instanceNamed("B") as? B
let a2 = manager.instanceNamed("A") as? A

print("a = \(a?.foo)")
print("a2 = \(a?.foo)")
print("b = \(b?.bar)")

关于ios - 将 Objective-C 动态绑定(bind)转换为 swift 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38283433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com