首页 > 解决方案 > 就性能而言,在多个地方调用捆绑构造函数是否昂贵?

问题描述

我需要在应用程序的不同部分使用 bundleWithPath: 至少 1000 次。

func someMethod() -> String {
    let path = Bundle(for: SomeClass.self).path(forResource: "someResource"),
    let bundle = Bundle(path: path)
    return bundle.someMethodReturningString
}

Bundle(path 在性能方面是否昂贵?我是否需要保留参考以避免多个实例?

标签: iosswiftperformancebundle

解决方案


根据文档,答案是否定的

仅当没有与 fullPath 关联的现有捆绑包时,这些构造函数才会初始化并返回一个新实例,否则它会释放 self 并返回现有对象。

斯威夫特文档

init(for: AnyClass)
Returns the NSBundle object with which the specified class is associated.

init?(identifier: String)
Returns the NSBundle instance that has the specified bundle identifier.

init?(url: URL)
Returns an NSBundle object initialized to correspond to the specified file URL.

init?(path: String)
Returns an NSBundle object initialized to correspond to the specified directory.

Objective-C

+ bundleWithURL:
Returns an NSBundle object that corresponds to the specified file URL.

+ bundleWithPath:
Returns an NSBundle object that corresponds to the specified directory.

+ bundleForClass:
Returns the NSBundle object with which the specified class is associated.

+ bundleWithIdentifier:
Returns the NSBundle instance that has the specified bundle identifier.

- initWithURL:
Returns an NSBundle object initialized to correspond to the specified file URL.

推荐阅读