LKS_ObjectRegistry.m 1.2 KB

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