Swift 3의 NotificationCenter 문제
저는 Swift 3을 배우고 있으며
NSNotificationCenter
. 내 코드는 다음과 같습니다.
func savePost(){
let postData = NSKeyedArchiver.archivedData(withRootObject: _loadedpost)
UserDefaults.standard().object(forKey: KEY_POST)
}
func loadPost(){
if let postData = UserDefaults.standard().object(forKey: KEY_POST) as? NSData{
if let postArray = NSKeyedUnarchiver.unarchiveObject(with: postData as Data) as? [Post]{
_loadedpost = postArray
}
}
//codeerror
NotificationCenter.default().post(NSNotification(name: "loadedPost" as NSNotification.Name, object: nil) as Notification)
}
그리고 이것은 관찰자입니다.
override func viewDidLoad() {
super.viewDidLoad()
//codeerorr
NotificationCenter.default().addObserver(self, selector: Selector(("onPostLoaded")), name: "loadedPost", object: nil)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
항상 "신호 SIGBRT"라는 오류가 발생합니다. 관찰자에서 이름을 변경하려고하면 오류는 아니지만 분명히 아무것도 표시되지 않았습니다. 이 문제를 어떻게 해결합니까?
스위프트 3 & 4
Swift 3 및 현재 Swift 4
struct
는 NotificationCenter의 경우와 같이 많은 "문자열 유형"API를 "래퍼 유형"으로 대체했습니다 . 알림은 이제로가
struct Notfication.Name
아닌로 식별 됩니다
String
. 자세한 내용은 현재 레거시 Swift 3로 마이그레이션 가이드를 참조하세요.
Swift 2.2
사용법 :
// Define identifier
let notificationIdentifier: String = "NotificationIdentifier"
// Register to receive notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name: notificationIdentifier, object: nil)
// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationIdentifier, object: nil)
Swift 3 및 4
사용 :
// Define identifier
let notificationName = Notification.Name("NotificationIdentifier")
// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification), name: notificationName, object: nil)
// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)
// Stop listening notification
NotificationCenter.default.removeObserver(self, name: notificationName, object: nil)
이제 모든 시스템 알림 유형이에 정적 상수로 정의됩니다
Notification.Name
. 즉
.UIApplicationDidFinishLaunching
,,
.UITextFieldTextDidChange
등
Notification.Name
시스템 알림과 일관성을 유지하기 위해 고유 한 사용자 지정 알림으로 확장 할 수 있습니다 .
// Definition:
extension Notification.Name {
static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}
// Usage:
NotificationCenter.default.post(name: .yourCustomNotificationName, object: nil)
Swift 4.2
사용법 :시스템 알림 이름이 UIApplication의 일부라는 점을 제외하면 Swift 4와 동일합니다. 따라서 시스템 알림과 일관성을 유지하기 위해
UIApplication
Notification.Name 대신 사용자 지정 알림으로 확장 할 수 있습니다 .
// Definition:
UIApplication {
public static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}
// Usage:
NotificationCenter.default.post(name: UIApplication.yourCustomNotificationName, object: nil)
Swift 3 또는 Swift 4에서 #selector를 사용하는 모든 문제를 해결하기 위해 여기에 전체 코드 예제가 있습니다.
// WE NEED A CLASS THAT SHOULD RECEIVE NOTIFICATIONS
class MyReceivingClass {
// ---------------------------------------------
// INIT -> GOOD PLACE FOR REGISTERING
// ---------------------------------------------
init() {
// WE REGISTER FOR SYSTEM NOTIFICATION (APP WILL RESIGN ACTIVE)
// Register without parameter
NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handleNotification), name: .UIApplicationWillResignActive, object: nil)
// Register WITH parameter
NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handle(withNotification:)), name: .UIApplicationWillResignActive, object: nil)
}
// ---------------------------------------------
// DE-INIT -> LAST OPTION FOR RE-REGISTERING
// ---------------------------------------------
deinit {
NotificationCenter.default.removeObserver(self)
}
// either "MyReceivingClass" must be a subclass of NSObject OR selector-methods MUST BE signed with '@objc'
// ---------------------------------------------
// HANDLE NOTIFICATION WITHOUT PARAMETER
// ---------------------------------------------
@objc func handleNotification() {
print("RECEIVED ANY NOTIFICATION")
}
// ---------------------------------------------
// HANDLE NOTIFICATION WITH PARAMETER
// ---------------------------------------------
@objc func handle(withNotification notification : NSNotification) {
print("RECEIVED SPECIFIC NOTIFICATION: \(notification)")
}
}
이 예제에서는 AppDelegate에서 POST를 가져 오려고합니다 (AppDelegate에서이를 구현합니다).
// ---------------------------------------------
// WHEN APP IS GOING TO BE INACTIVE
// ---------------------------------------------
func applicationWillResignActive(_ application: UIApplication) {
print("POSTING")
// Define identifiyer
let notificationName = Notification.Name.UIApplicationWillResignActive
// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)
}
알림이 다시 변경된 것 같습니다 (2016 년 10 월).
// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(yourClass.yourMethod), name: NSNotification.Name(rawValue: "yourNotificatioName"), object: nil)
// Post notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "yourNotificationName"), object: nil)
I think it has changed again.
For posting this works in Xcode 8.2.
NotificationCenter.default.post(Notification(name:.UIApplicationWillResignActive)
참고URL : https://stackoverflow.com/questions/38204703/notificationcenter-issue-on-swift-3
'IT박스' 카테고리의 다른 글
Notepad ++-빈 줄을 어떻게 바꿀 수 있습니까? (0) | 2020.09.02 |
---|---|
파이썬-파이썬에서 URL의 유효성을 검사하는 방법은 무엇입니까? (0) | 2020.09.02 |
C / C # / C ++에서 역방향 루프를 수행하는 가장 좋은 방법은 무엇입니까? (0) | 2020.09.02 |
행을 계산하는 Android의 SQLite 쿼리 (0) | 2020.09.02 |
Storyboard에서 간단한 둥근 버튼을 만드는 방법은 무엇입니까? (0) | 2020.09.02 |