FLEXLiveObjectsController.m 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. //
  2. // FLEXLiveObjectsController.m
  3. // Flipboard
  4. //
  5. // Created by Ryan Olson on 5/28/14.
  6. // Copyright (c) 2020 FLEX Team. All rights reserved.
  7. //
  8. #import "FLEXLiveObjectsController.h"
  9. #import "FLEXHeapEnumerator.h"
  10. #import "FLEXObjectListViewController.h"
  11. #import "FLEXUtility.h"
  12. #import "FLEXScopeCarousel.h"
  13. #import "FLEXTableView.h"
  14. #import <objc/runtime.h>
  15. static const NSInteger kFLEXLiveObjectsSortAlphabeticallyIndex = 0;
  16. static const NSInteger kFLEXLiveObjectsSortByCountIndex = 1;
  17. static const NSInteger kFLEXLiveObjectsSortBySizeIndex = 2;
  18. @interface FLEXLiveObjectsController ()
  19. @property (nonatomic) NSDictionary<NSString *, NSNumber *> *instanceCountsForClassNames;
  20. @property (nonatomic) NSDictionary<NSString *, NSNumber *> *instanceSizesForClassNames;
  21. @property (nonatomic, readonly) NSArray<NSString *> *allClassNames;
  22. @property (nonatomic) NSArray<NSString *> *filteredClassNames;
  23. @property (nonatomic) NSString *headerTitle;
  24. @end
  25. @implementation FLEXLiveObjectsController
  26. - (void)viewDidLoad {
  27. [super viewDidLoad];
  28. self.showsSearchBar = YES;
  29. self.showSearchBarInitially = YES;
  30. self.searchBarDebounceInterval = kFLEXDebounceInstant;
  31. self.showsCarousel = YES;
  32. self.carousel.items = @[@"A→Z", @"Count", @"Size"];
  33. self.refreshControl = [UIRefreshControl new];
  34. [self.refreshControl addTarget:self action:@selector(refreshControlDidRefresh:) forControlEvents:UIControlEventValueChanged];
  35. [self reloadTableData];
  36. }
  37. - (NSArray<NSString *> *)allClassNames {
  38. return self.instanceCountsForClassNames.allKeys;
  39. }
  40. - (void)reloadTableData {
  41. // Set up a CFMutableDictionary with class pointer keys and NSUInteger values.
  42. // We abuse CFMutableDictionary a little to have primitive keys through judicious casting, but it gets the job done.
  43. // The dictionary is intialized with a 0 count for each class so that it doesn't have to expand during enumeration.
  44. // While it might be a little cleaner to populate an NSMutableDictionary with class name string keys to NSNumber counts,
  45. // we choose the CF/primitives approach because it lets us enumerate the objects in the heap without allocating any memory during enumeration.
  46. // The alternative of creating one NSString/NSNumber per object on the heap ends up polluting the count of live objects quite a bit.
  47. unsigned int classCount = 0;
  48. Class *classes = objc_copyClassList(&classCount);
  49. CFMutableDictionaryRef mutableCountsForClasses = CFDictionaryCreateMutable(NULL, classCount, NULL, NULL);
  50. for (unsigned int i = 0; i < classCount; i++) {
  51. CFDictionarySetValue(mutableCountsForClasses, (__bridge const void *)classes[i], (const void *)0);
  52. }
  53. // Enumerate all objects on the heap to build the counts of instances for each class.
  54. [FLEXHeapEnumerator enumerateLiveObjectsUsingBlock:^(__unsafe_unretained id object, __unsafe_unretained Class actualClass) {
  55. NSUInteger instanceCount = (NSUInteger)CFDictionaryGetValue(mutableCountsForClasses, (__bridge const void *)actualClass);
  56. instanceCount++;
  57. CFDictionarySetValue(mutableCountsForClasses, (__bridge const void *)actualClass, (const void *)instanceCount);
  58. }];
  59. // Convert our CF primitive dictionary into a nicer mapping of class name strings to counts that we will use as the table's model.
  60. NSMutableDictionary<NSString *, NSNumber *> *mutableCountsForClassNames = [NSMutableDictionary new];
  61. NSMutableDictionary<NSString *, NSNumber *> *mutableSizesForClassNames = [NSMutableDictionary new];
  62. for (unsigned int i = 0; i < classCount; i++) {
  63. Class class = classes[i];
  64. NSUInteger instanceCount = (NSUInteger)CFDictionaryGetValue(mutableCountsForClasses, (__bridge const void *)(class));
  65. NSString *className = @(class_getName(class));
  66. if (instanceCount > 0) {
  67. [mutableCountsForClassNames setObject:@(instanceCount) forKey:className];
  68. }
  69. [mutableSizesForClassNames setObject:@(class_getInstanceSize(class)) forKey:className];
  70. }
  71. free(classes);
  72. self.instanceCountsForClassNames = mutableCountsForClassNames;
  73. self.instanceSizesForClassNames = mutableSizesForClassNames;
  74. [self updateSearchResults:nil];
  75. }
  76. - (void)refreshControlDidRefresh:(id)sender {
  77. [self reloadTableData];
  78. [self.refreshControl endRefreshing];
  79. }
  80. - (void)updateHeaderTitle {
  81. NSUInteger totalCount = 0;
  82. NSUInteger totalSize = 0;
  83. for (NSString *className in self.allClassNames) {
  84. NSUInteger count = self.instanceCountsForClassNames[className].unsignedIntegerValue;
  85. totalCount += count;
  86. totalSize += count * self.instanceSizesForClassNames[className].unsignedIntegerValue;
  87. }
  88. NSUInteger filteredCount = 0;
  89. NSUInteger filteredSize = 0;
  90. for (NSString *className in self.filteredClassNames) {
  91. NSUInteger count = self.instanceCountsForClassNames[className].unsignedIntegerValue;
  92. filteredCount += count;
  93. filteredSize += count * self.instanceSizesForClassNames[className].unsignedIntegerValue;
  94. }
  95. if (filteredCount == totalCount) {
  96. // Unfiltered
  97. self.headerTitle = [NSString
  98. stringWithFormat:@"%@ objects, %@",
  99. @(totalCount), [NSByteCountFormatter
  100. stringFromByteCount:totalSize
  101. countStyle:NSByteCountFormatterCountStyleFile
  102. ]
  103. ];
  104. } else {
  105. self.headerTitle = [NSString
  106. stringWithFormat:@"%@ of %@ objects, %@",
  107. @(filteredCount), @(totalCount), [NSByteCountFormatter
  108. stringFromByteCount:filteredSize
  109. countStyle:NSByteCountFormatterCountStyleFile
  110. ]
  111. ];
  112. }
  113. }
  114. #pragma mark - FLEXGlobalsEntry
  115. + (NSString *)globalsEntryTitle:(FLEXGlobalsRow)row {
  116. return @"💩 Heap Objects";
  117. }
  118. + (UIViewController *)globalsEntryViewController:(FLEXGlobalsRow)row {
  119. FLEXLiveObjectsController *liveObjectsViewController = [self new];
  120. liveObjectsViewController.title = [self globalsEntryTitle:row];
  121. return liveObjectsViewController;
  122. }
  123. #pragma mark - Search bar
  124. - (void)updateSearchResults:(NSString *)filter {
  125. NSInteger selectedScope = self.selectedScope;
  126. if (filter.length) {
  127. NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", filter];
  128. self.filteredClassNames = [self.allClassNames filteredArrayUsingPredicate:searchPredicate];
  129. } else {
  130. self.filteredClassNames = self.allClassNames;
  131. }
  132. if (selectedScope == kFLEXLiveObjectsSortAlphabeticallyIndex) {
  133. self.filteredClassNames = [self.filteredClassNames sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
  134. } else if (selectedScope == kFLEXLiveObjectsSortByCountIndex) {
  135. self.filteredClassNames = [self.filteredClassNames sortedArrayUsingComparator:^NSComparisonResult(NSString *className1, NSString *className2) {
  136. NSNumber *count1 = self.instanceCountsForClassNames[className1];
  137. NSNumber *count2 = self.instanceCountsForClassNames[className2];
  138. // Reversed for descending counts.
  139. return [count2 compare:count1];
  140. }];
  141. } else if (selectedScope == kFLEXLiveObjectsSortBySizeIndex) {
  142. self.filteredClassNames = [self.filteredClassNames sortedArrayUsingComparator:^NSComparisonResult(NSString *className1, NSString *className2) {
  143. NSNumber *count1 = self.instanceCountsForClassNames[className1];
  144. NSNumber *count2 = self.instanceCountsForClassNames[className2];
  145. NSNumber *size1 = self.instanceSizesForClassNames[className1];
  146. NSNumber *size2 = self.instanceSizesForClassNames[className2];
  147. // Reversed for descending sizes.
  148. return [@(count2.integerValue * size2.integerValue) compare:@(count1.integerValue * size1.integerValue)];
  149. }];
  150. }
  151. [self updateHeaderTitle];
  152. [self.tableView reloadData];
  153. }
  154. #pragma mark - Table view data source
  155. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  156. return 1;
  157. }
  158. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  159. return self.filteredClassNames.count;
  160. }
  161. - (UITableViewCell *)tableView:(__kindof UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  162. UITableViewCell *cell = [tableView
  163. dequeueReusableCellWithIdentifier:kFLEXDefaultCell
  164. forIndexPath:indexPath
  165. ];
  166. NSString *className = self.filteredClassNames[indexPath.row];
  167. NSNumber *count = self.instanceCountsForClassNames[className];
  168. NSNumber *size = self.instanceSizesForClassNames[className];
  169. unsigned long totalSize = count.unsignedIntegerValue * size.unsignedIntegerValue;
  170. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  171. cell.textLabel.text = [NSString stringWithFormat:@"%@ (%ld, %@)",
  172. className, (long)[count integerValue],
  173. [NSByteCountFormatter
  174. stringFromByteCount:totalSize
  175. countStyle:NSByteCountFormatterCountStyleFile
  176. ]
  177. ];
  178. return cell;
  179. }
  180. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
  181. return self.headerTitle;
  182. }
  183. #pragma mark - Table view delegate
  184. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  185. NSString *className = self.filteredClassNames[indexPath.row];
  186. UIViewController *instances = [FLEXObjectListViewController instancesOfClassWithName:className];
  187. [self.navigationController pushViewController:instances animated:YES];
  188. }
  189. @end