مثال لإشعارات الكاكاو المخصصة
-
20-08-2019 - |
سؤال
هل يمكن لأي شخص أن يريني مثالاً لكائن Cocoa Obj-C، مع إشعار مخصص، وكيفية تشغيله والاشتراك فيه والتعامل معه؟
المحلول
@implementation MyObject
// Posts a MyNotification message whenever called
- (void)notify {
[[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:self];
}
// Prints a message whenever a MyNotification is received
- (void)handleNotification:(NSNotification*)note {
NSLog(@"Got notified: %@", note);
}
@end
// somewhere else
MyObject *object = [[MyObject alloc] init];
// receive MyNotification events from any object
[[NSNotificationCenter defaultCenter] addObserver:object selector:@selector(handleNotification:) name:@"MyNotification" object:nil];
// create a notification
[object notify];
لمزيد من المعلومات، راجع وثائق <وأ href = "http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html#//apple_ref/doc/ رمز المستخدم / 20000219-2831 "يختلط =" noreferrer "> NSNotificationCenter .
نصائح أخرى
الخطوة 1:
//register to listen for event
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(eventHandler:)
name:@"eventType"
object:nil ];
//event handler when event occurs
-(void)eventHandler: (NSNotification *) notification
{
NSLog(@"event triggered");
}
الخطوة 2:
//trigger event
[[NSNotificationCenter defaultCenter]
postNotificationName:@"eventType"
object:nil ];
تأكد من إلغاء تسجيل الإعلام (مراقب) عندما يتم deallocated الكائن. وتنص الوثائق أبل: "قبل أن يتم deallocated كائن يتم مراقبة الإخطارات، يجب أن نقول للمركز الإعلام لوقف إرسال اخطاران".
لالإخطارات المحلية الرمز التالي هو تطبيق:
[[NSNotificationCenter defaultCenter] removeObserver:self];
وبالنسبة للمراقبين الإخطارات توزيع:
[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
لا تنتمي إلى StackOverflow