質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

1回答

4009閲覧

UIApplication.shared.openのsharedとopenの関係

pegy

総合スコア243

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2020/05/24 05:30

ネイティブアプリでブラウザを開くコードを試しに記述していてUIApplication.shared.openというコードに当たって、Jump to Definitionで以下の様な情報を取得しました。

不慣れでdocumentationの見方がわからずに教えていただきたいのですが、UIApplicarionクラスにおいて、sharedopenはそれぞれどの様な関係であり、documentationからどの様にして読み解くことができるのでしょうか?


素人なりの見方なのですが、以下のようんに読み取れます。
1.UIApplication : UIResponder
上記からからUIApplicationクラスはUIResponderクラスを承継している。

2.open class UIApplication : UIResponder {open class var shared: UIApplication { get }
上記からshareはUIApplicationの中のクラス(サブクラス)である。

3.@available(iOS 10.0, *) open func open(_ url: URL, options: [UIApplication.OpenExternalURLOptionsKey : Any] = [:], completionHandler completion: ((Bool) -> Void)? = nil)
上記から、open()はUIApplicationクラスのメソッドである。


(質問1)
上記の2.に関連してこのsharedクラスはUIApplicationクラスにおいてどの様な役割と読み解けば良いのでしょうか?open class var shared: UIApplication { get }と記載されても親クラスとの関係や役割について、見方がわからない状況です。。。

(質問2)
上記の1.3.からopen()メソッドは単純にUIApplicationクラスのメソッドに見える(なぜなら俯瞰してみるとUIApplication {open()}の様な説明に読み取れるため)のですが、そうするとUIApplication.open()いい様に思えるのですが、なぜUIApplication.shared.openなのでしょうか?もしかすると(質問1)とも関連するかもしれませんが、教えてください。

documentation

1@available(iOS 2.0, *) 2open class UIApplication : UIResponder { 3 4 5 open class var shared: UIApplication { get } 6 7 8 unowned(unsafe) open var delegate: UIApplicationDelegate? 9 10 11 @available(iOS, introduced: 2.0, deprecated: 13.0, message: "Use UIView's userInteractionEnabled property instead") 12 open func beginIgnoringInteractionEvents() // nested. set should be set during animations & transitions to ignore touch and other events 13 14 @available(iOS, introduced: 2.0, deprecated: 13.0, message: "Use UIView's userInteractionEnabled property instead") 15 open func endIgnoringInteractionEvents() 16 17 @available(iOS, introduced: 2.0, deprecated: 13.0, message: "Use UIView's userInteractionEnabled property instead") 18 open var isIgnoringInteractionEvents: Bool { get } // returns YES if we are at least one deep in ignoring events 19 20 21 open var isIdleTimerDisabled: Bool // default is NO 22 23 24 @available(iOS, introduced: 2.0, deprecated: 10.0) 25 open func openURL(_ url: URL) -> Bool 26 27 @available(iOS 3.0, *) 28 open func canOpenURL(_ url: URL) -> Bool 29 30 31 // Options are specified in the section below for openURL options. An empty options dictionary will result in the same 32 // behavior as the older openURL call, aside from the fact that this is asynchronous and calls the completion handler rather 33 // than returning a result. 34 // The completion handler is called on the main queue. 35 @available(iOS 10.0, *) 36 open func open(_ url: URL, options: [UIApplication.OpenExternalURLOptionsKey : Any] = [:], completionHandler completion: ((Bool) -> Void)? = nil) 37 38 39 open func sendEvent(_ event: UIEvent) 40 41 42 @available(iOS, introduced: 2.0, deprecated: 13.0, message: "Should not be used for applications that support multiple scenes as it returns a key window across all connected scenes") 43 open var keyWindow: UIWindow? { get } 44 45 open var windows: [UIWindow] { get } 46 47 48 open func sendAction(_ action: Selector, to target: Any?, from sender: Any?, for event: UIEvent?) -> Bool 49 50 51 @available(iOS, introduced: 2.0, deprecated: 13.0, message: "Provide a custom network activity UI in your app if desired.") 52 open var isNetworkActivityIndicatorVisible: Bool 53 54 55 @available(iOS, introduced: 2.0, deprecated: 13.0, message: "Use the statusBarManager property of the window scene instead.") 56 open var statusBarStyle: UIStatusBarStyle { get } // default is UIStatusBarStyleDefault 57 58 59 @available(iOS, introduced: 2.0, deprecated: 13.0, message: "Use the statusBarManager property of the window scene instead.") 60 open var isStatusBarHidden: Bool { get } 61 62 63 @available(iOS, introduced: 2.0, deprecated: 13.0, message: "Use the interfaceOrientation property of the window scene instead.") 64 open var statusBarOrientation: UIInterfaceOrientation { get } 65 66 67 // The system only calls this method if the application delegate has not 68 // implemented the delegate equivalent. It returns the orientations specified by 69 // the application's info.plist. If no supported interface orientations were 70 // specified it will return UIInterfaceOrientationMaskAll on an iPad and 71 // UIInterfaceOrientationMaskAllButUpsideDown on a phone. The return value 72 // should be one of the UIInterfaceOrientationMask values which indicates the 73 // orientations supported by this application. 74 @available(iOS 6.0, *) 75 open func supportedInterfaceOrientations(for window: UIWindow?) -> UIInterfaceOrientationMask 76 77 78 @available(iOS, introduced: 2.0, deprecated: 13.0, message: "Use viewWillTransitionToSize:withTransitionCoordinator: instead.") 79 open var statusBarOrientationAnimationDuration: TimeInterval { get } // Returns the animation duration for the status bar during a 90 degree orientation change. It should be doubled for a 180 degree orientation change. 80 81 @available(iOS, introduced: 2.0, deprecated: 13.0, message: "Use the statusBarManager property of the window scene instead.") 82 open var statusBarFrame: CGRect { get } // returns CGRectZero if the status bar is hidden 83 84 85 open var applicationIconBadgeNumber: Int // set to 0 to hide. default is 0. In iOS 8.0 and later, your application must register for user notifications using -[UIApplication registerUserNotificationSettings:] before being able to set the icon badge. 86 87 88 @available(iOS 3.0, *) 89 open var applicationSupportsShakeToEdit: Bool 90 91 92 @available(iOS 4.0, *) 93 open var applicationState: UIApplication.State { get } 94 95 @available(iOS 4.0, *) 96 open var backgroundTimeRemaining: TimeInterval { get } 97 98 99 @available(iOS 4.0, *) 100 open func beginBackgroundTask(expirationHandler handler: (() -> Void)? = nil) -> UIBackgroundTaskIdentifier 101 102 @available(iOS 7.0, *) 103 open func beginBackgroundTask(withName taskName: String?, expirationHandler handler: (() -> Void)? = nil) -> UIBackgroundTaskIdentifier 104 105 @available(iOS 4.0, *) 106 open func endBackgroundTask(_ identifier: UIBackgroundTaskIdentifier) 107 108 109 /** The system guarantees that it will not wake up your application for a background fetch more 110 frequently than the interval provided. Set to UIApplicationBackgroundFetchIntervalMinimum to be 111 woken as frequently as the system desires, or to UIApplicationBackgroundFetchIntervalNever (the 112 default) to never be woken for a background fetch. 113 114 This setter will have no effect unless your application has the "fetch" 115 UIBackgroundMode. See the UIApplicationDelegate method 116 `application:performFetchWithCompletionHandler:` for more. */ 117 @available(iOS, introduced: 7.0, deprecated: 13.0, message: "Use a BGAppRefreshTask in the BackgroundTasks framework instead") 118 open func setMinimumBackgroundFetchInterval(_ minimumBackgroundFetchInterval: TimeInterval) 119 120 121 /** When background refresh is available for an application, it may launched or resumed in the background to handle significant 122 location changes, remote notifications, background fetches, etc. Observe UIApplicationBackgroundRefreshStatusDidChangeNotification to 123 be notified of changes. */ 124 @available(iOS 7.0, *) 125 open var backgroundRefreshStatus: UIBackgroundRefreshStatus { get } 126 127 128 @available(iOS 4.0, *) 129 open var isProtectedDataAvailable: Bool { get } 130 131 132 @available(iOS 5.0, *) 133 open var userInterfaceLayoutDirection: UIUserInterfaceLayoutDirection { get } 134 135 136 // Return the size category 137 @available(iOS 7.0, *) 138 open var preferredContentSizeCategory: UIContentSizeCategory { get } 139 140 141 // All of the currently connected UIScene instances 142 @available(iOS 13.0, *) 143 open var connectedScenes: Set<UIScene> { get } 144 145 146 // All of the representations that currently have connected UIScene instances or had their sessions persisted by the system (ex: visible in iOS' switcher) 147 @available(iOS 13.0, *) 148 open var openSessions: Set<UISceneSession> { get } 149 150 151 // returns YES if the application both declares multiple scene support in its info.plist and the executing environment allows multiple scenes for at least one system type. NO otherwise. 152 @available(iOS 13.0, *) 153 open var supportsMultipleScenes: Bool { get } 154 155 156 // Request a given session be activated, first connecting it to the application if necessary. 157 // Providing a session will activate, connecting if necessary, the interface backed by the already existing UISceneSession. 158 // Providing a user activity will dispatch that activity to the provided session's scene. If no session is provided, then the system will select one (possibly creating a new session, if appropriate) and pass the activity to the session scene's delegate. 159 @available(iOS 13.0, *) 160 open func requestSceneSessionActivation(_ sceneSession: UISceneSession?, userActivity: NSUserActivity?, options: UIScene.ActivationRequestOptions?, errorHandler: ((Error) -> Void)? = nil) 161 162 163 // requests that a given session be closed, disconnecting the currently connected scene if present, and calling the -application:didDiscardSceneSessions: method on the application's delegate 164 @available(iOS 13.0, *) 165 open func requestSceneSessionDestruction(_ sceneSession: UISceneSession, options: UISceneDestructionRequestOptions?, errorHandler: ((Error) -> Void)? = nil) 166 167 168 // requests that any system UI representing a scene be updated due to background updates or any other relevant model/state update. 169 @available(iOS 13.0, *) 170 open func requestSceneSessionRefresh(_ sceneSession: UISceneSession) 171}

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

pegy

2020/05/24 15:00

コメントありがとうございます! いろいろな記事を読んでも「シングルトンパターンはインスタンスが1個しか生成されないことを保証したい時に使います」の意味するところが実はまだピントはこない?(そんなケースなんてあるのか?)という素人丸出しの状況ですが、その様なものがあることはよくわかりました!
pegy

2020/05/24 15:11

変化を加えたインスタンスを流用して使いたい(新たにインスタンス化して0から作り直す)場合などに使われるのですね。車のボディをインスタンスに化したものを①ヘッドライトを付けたとして(プロパティを設定)、そこから②タイヤをつける場合、タイヤAとタイヤBをつけるパターンについて、ボディからインスタンス化したものをまた、①の手続を減るのはナンセンスなのでシングルトンを利用して使い回す様ないめーじでいます。稚拙な発想で恐縮ですが。。
hoshi-takanori

2020/05/24 15:53 編集

シングルトンの説明には「インスタンス 1 個だけ〜」と書いてあることが多いですし、UIApplication はアプリそのものを管理するものなので一つのアプリ内に複数あっても困りますが、iOS のフレームワークでは、「どうしてもって言うなら複数作ってもいいけど、とりあえずデフォルトのインスタンスが 1 個あると便利でしょ」くらいのノリで使われてることも結構ある気がします。UserDefaults.shared とか。
guest

回答1

0

ベストアンサー

以下のAppleDeveloperDocumentを参考に回答させて頂きます。
こちらの解釈が誤っていたら、どなたかご訂正ください。。

質問1について
sharedはクラスではなく、UIApplicationクラスのプロパティ。
(UIApplicationクラスのインスタンスを取得できるプロパティ)

質問2について
openはインスタンスメソッドなので、インスタンス経由しないと実行できない。
したがって、sharedでインスタンスを取得した後に、openを呼ばないといけない。
(上記の一連の経緯があり、UIApplication.shared.openという記載になる)

投稿2020/05/24 11:11

tsuki01

総合スコア1751

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

pegy

2020/05/24 13:13

コメントありがとうございます。 sharedはシングルトン的な物であることがわかりました。おそらくクラスプロパティを使って、UIApplicationクラスのインスタンスを取得して、インスタンスメソッドを呼び出すという手続と解釈いたしました。細かい仕様や動作については、正直まだまだわからないことがSwiftはたくさんありますが、とりあえず、その様な手続(方法)があるということを身に付けようと思います。
tsuki01

2020/05/24 13:44

解決した様で良かったです。質問を閉じて頂きありがとうございました。 hoshi-takanori様からの補足コメントもありましたが、シングルトンオブジェクトという解釈で問題ありません。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問