LKS_ObjectRegistry.m 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #ifdef SHOULD_COMPILE_LOOKIN_SERVER
  2. //
  3. // LKS_ObjectRegistry.m
  4. // LookinServer
  5. //
  6. // Created by Li Kai on 2019/4/21.
  7. // https://lookin.work
  8. //
  9. #import "LKS_ObjectRegistry.h"
  10. #import <objc/runtime.h>
  11. @interface LKS_ObjectRegistry ()
  12. @property(nonatomic, strong) NSPointerArray *data;
  13. @end
  14. @implementation LKS_ObjectRegistry
  15. + (instancetype)sharedInstance {
  16. static dispatch_once_t onceToken;
  17. static LKS_ObjectRegistry *instance = nil;
  18. dispatch_once(&onceToken,^{
  19. instance = [[super allocWithZone:NULL] init];
  20. });
  21. return instance;
  22. }
  23. + (id)allocWithZone:(struct _NSZone *)zone{
  24. return [self sharedInstance];
  25. }
  26. - (instancetype)init {
  27. if (self = [super init]) {
  28. self.data = [NSPointerArray weakObjectsPointerArray];
  29. // index 为 0 用 Null 填充
  30. self.data.count = 1;
  31. }
  32. return self;
  33. }
  34. - (unsigned long)addObject:(NSObject *)object {
  35. if (!object) {
  36. return 0;
  37. }
  38. [self.data addPointer:(void *)object];
  39. return self.data.count - 1;
  40. }
  41. - (NSObject *)objectWithOid:(unsigned long)oid {
  42. if (self.data.count <= oid) {
  43. return nil;
  44. }
  45. id object = [self.data pointerAtIndex:oid];
  46. return object;
  47. }
  48. @end
  49. #endif /* SHOULD_COMPILE_LOOKIN_SERVER */