为什么我在 Swift 中使用 NSBundle 之前不必导入 Foundation?
Why don't I have to import Foundation before using NSBundle in Swift?
在我下面的代码中,我使用的是 NSBundle。根据文档(https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSBundle_Class/#//apple_ref/occ/clm/NSBundle/bundleWithURL:),您需要导入 Foundation 才能使用 NSBundle。
但是,在我下面的代码中,我没有导入 Foundation,但我可以使用 NSBundle。这是为什么?
我想可能是因为我导入了AVFoundation,而AVFoundation继承自NSObject;但是,当我阅读文档时,AVFoundation 并未列为从 NSObject 继承而来。
import UIKit
import AVFoundation
class PlaySoundsViewController: UIViewController {
var audioPlayer:AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if var filePath = NSBundle.mainBundle().pathForResource("movie_quote", ofType: "mp3") {
var filePathUrl = NSURL.fileURLWithPath(filePath)
audioPlayer = AVAudioPlayer(contentsOfURL: filePathUrl, error: nil)
}else {
println("the file path is empty")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func playSlowAudio(sender: UIButton) {
audioPlayer.play()
}
}
UIKit
导入 Foundation
并且您继承任何您公开导入的东西。
在我下面的代码中,我使用的是 NSBundle。根据文档(https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSBundle_Class/#//apple_ref/occ/clm/NSBundle/bundleWithURL:),您需要导入 Foundation 才能使用 NSBundle。
但是,在我下面的代码中,我没有导入 Foundation,但我可以使用 NSBundle。这是为什么?
我想可能是因为我导入了AVFoundation,而AVFoundation继承自NSObject;但是,当我阅读文档时,AVFoundation 并未列为从 NSObject 继承而来。
import UIKit
import AVFoundation
class PlaySoundsViewController: UIViewController {
var audioPlayer:AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if var filePath = NSBundle.mainBundle().pathForResource("movie_quote", ofType: "mp3") {
var filePathUrl = NSURL.fileURLWithPath(filePath)
audioPlayer = AVAudioPlayer(contentsOfURL: filePathUrl, error: nil)
}else {
println("the file path is empty")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func playSlowAudio(sender: UIButton) {
audioPlayer.play()
}
}
UIKit
导入 Foundation
并且您继承任何您公开导入的东西。