NSNotificationCenter+YYAdd.m 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //
  2. // NSNotificationCenter+YYAdd.m
  3. // YYKit <https://github.com/ibireme/YYKit>
  4. //
  5. // Created by ibireme on 13/8/24.
  6. // Copyright (c) 2015 ibireme.
  7. //
  8. // This source code is licensed under the MIT-style license found in the
  9. // LICENSE file in the root directory of this source tree.
  10. //
  11. #import "NSNotificationCenter+YYAdd.h"
  12. #include <pthread.h>
  13. #import "YYKitMacro.h"
  14. YYSYNTH_DUMMY_CLASS(NSNotificationCenter_YYAdd)
  15. @implementation NSNotificationCenter (YYAdd)
  16. - (void)postNotificationOnMainThread:(NSNotification *)notification {
  17. if (pthread_main_np()) return [self postNotification:notification];
  18. [self postNotificationOnMainThread:notification waitUntilDone:NO];
  19. }
  20. - (void)postNotificationOnMainThread:(NSNotification *)notification waitUntilDone:(BOOL)wait {
  21. if (pthread_main_np()) return [self postNotification:notification];
  22. [[self class] performSelectorOnMainThread:@selector(_yy_postNotification:) withObject:notification waitUntilDone:wait];
  23. }
  24. - (void)postNotificationOnMainThreadWithName:(NSString *)name object:(id)object {
  25. if (pthread_main_np()) return [self postNotificationName:name object:object userInfo:nil];
  26. [self postNotificationOnMainThreadWithName:name object:object userInfo:nil waitUntilDone:NO];
  27. }
  28. - (void)postNotificationOnMainThreadWithName:(NSString *)name object:(id)object userInfo:(NSDictionary *)userInfo {
  29. if (pthread_main_np()) return [self postNotificationName:name object:object userInfo:userInfo];
  30. [self postNotificationOnMainThreadWithName:name object:object userInfo:userInfo waitUntilDone:NO];
  31. }
  32. - (void)postNotificationOnMainThreadWithName:(NSString *)name object:(id)object userInfo:(NSDictionary *)userInfo waitUntilDone:(BOOL)wait {
  33. if (pthread_main_np()) return [self postNotificationName:name object:object userInfo:userInfo];
  34. NSMutableDictionary *info = [[NSMutableDictionary allocWithZone:nil] initWithCapacity:3];
  35. if (name) [info setObject:name forKey:@"name"];
  36. if (object) [info setObject:object forKey:@"object"];
  37. if (userInfo) [info setObject:userInfo forKey:@"userInfo"];
  38. [[self class] performSelectorOnMainThread:@selector(_yy_postNotificationName:) withObject:info waitUntilDone:wait];
  39. }
  40. + (void)_yy_postNotification:(NSNotification *)notification {
  41. [[self defaultCenter] postNotification:notification];
  42. }
  43. + (void)_yy_postNotificationName:(NSDictionary *)info {
  44. NSString *name = [info objectForKey:@"name"];
  45. id object = [info objectForKey:@"object"];
  46. NSDictionary *userInfo = [info objectForKey:@"userInfo"];
  47. [[self defaultCenter] postNotificationName:name object:object userInfo:userInfo];
  48. }
  49. @end