FLEXLiveObjectsController.m 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. - (void)viewDidAppear:(BOOL)animated {
  38. [super viewDidAppear:animated];
  39. dispatch_async(dispatch_get_main_queue(), ^{
  40. // This doesn't work unless it's wrapped in this dispatch_async call
  41. [self.searchController.searchBar becomeFirstResponder];
  42. });
  43. }
  44. - (NSArray<NSString *> *)allClassNames {
  45. return self.instanceCountsForClassNames.allKeys;
  46. }
  47. - (void)reloadTableData {
  48. // Set up a CFMutableDictionary with class pointer keys and NSUInteger values.
  49. // We abuse CFMutableDictionary a little to have primitive keys through judicious casting, but it gets the job done.
  50. // The dictionary is intialized with a 0 count for each class so that it doesn't have to expand during enumeration.
  51. // While it might be a little cleaner to populate an NSMutableDictionary with class name string keys to NSNumber counts,
  52. // we choose the CF/primitives approach because it lets us enumerate the objects in the heap without allocating any memory during enumeration.
  53. // The alternative of creating one NSString/NSNumber per object on the heap ends up polluting the count of live objects quite a bit.
  54. unsigned int classCount = 0;
  55. Class *classes = objc_copyClassList(&classCount);
  56. CFMutableDictionaryRef mutableCountsForClasses = CFDictionaryCreateMutable(NULL, classCount, NULL, NULL);
  57. for (unsigned int i = 0; i < classCount; i++) {
  58. CFDictionarySetValue(mutableCountsForClasses, (__bridge const void *)classes[i], (const void *)0);
  59. }
  60. // Enumerate all objects on the heap to build the counts of instances for each class.
  61. [FLEXHeapEnumerator enumerateLiveObjectsUsingBlock:^(__unsafe_unretained id object, __unsafe_unretained Class actualClass) {
  62. NSUInteger instanceCount = (NSUInteger)CFDictionaryGetValue(mutableCountsForClasses, (__bridge const void *)actualClass);
  63. instanceCount++;
  64. CFDictionarySetValue(mutableCountsForClasses, (__bridge const void *)actualClass, (const void *)instanceCount);
  65. }];
  66. // Convert our CF primitive dictionary into a nicer mapping of class name strings to counts that we will use as the table's model.
  67. NSMutableDictionary<NSString *, NSNumber *> *mutableCountsForClassNames = [NSMutableDictionary new];
  68. NSMutableDictionary<NSString *, NSNumber *> *mutableSizesForClassNames = [NSMutableDictionary new];
  69. for (unsigned int i = 0; i < classCount; i++) {
  70. Class class = classes[i];
  71. NSUInteger instanceCount = (NSUInteger)CFDictionaryGetValue(mutableCountsForClasses, (__bridge const void *)(class));
  72. NSString *className = @(class_getName(class));
  73. if (instanceCount > 0) {
  74. [mutableCountsForClassNames setObject:@(instanceCount) forKey:className];
  75. }
  76. [mutableSizesForClassNames setObject:@(class_getInstanceSize(class)) forKey:className];
  77. }
  78. free(classes);
  79. self.instanceCountsForClassNames = mutableCountsForClassNames;
  80. self.instanceSizesForClassNames = mutableSizesForClassNames;
  81. [self updateSearchResults:nil];
  82. }
  83. - (void)refreshControlDidRefresh:(id)sender {
  84. [self reloadTableData];
  85. [self.refreshControl endRefreshing];
  86. }
  87. - (void)updateHeaderTitle {
  88. NSUInteger totalCount = 0;
  89. NSUInteger totalSize = 0;
  90. for (NSString *className in self.allClassNames) {
  91. NSUInteger count = self.instanceCountsForClassNames[className].unsignedIntegerValue;
  92. totalCount += count;
  93. totalSize += count * self.instanceSizesForClassNames[className].unsignedIntegerValue;
  94. }
  95. NSUInteger filteredCount = 0;
  96. NSUInteger filteredSize = 0;
  97. for (NSString *className in self.filteredClassNames) {
  98. NSUInteger count = self.instanceCountsForClassNames[className].unsignedIntegerValue;
  99. filteredCount += count;
  100. filteredSize += count * self.instanceSizesForClassNames[className].unsignedIntegerValue;
  101. }
  102. if (filteredCount == totalCount) {
  103. // Unfiltered
  104. self.headerTitle = [NSString
  105. stringWithFormat:@"%@ objects, %@",
  106. @(totalCount), [NSByteCountFormatter
  107. stringFromByteCount:totalSize
  108. countStyle:NSByteCountFormatterCountStyleFile
  109. ]
  110. ];
  111. } else {
  112. self.headerTitle = [NSString
  113. stringWithFormat:@"%@ of %@ objects, %@",
  114. @(filteredCount), @(totalCount), [NSByteCountFormatter
  115. stringFromByteCount:filteredSize
  116. countStyle:NSByteCountFormatterCountStyleFile
  117. ]
  118. ];
  119. }
  120. }
  121. #pragma mark - FLEXGlobalsEntry
  122. + (NSString *)globalsEntryTitle:(FLEXGlobalsRow)row {
  123. return @"💩 Heap Objects";
  124. }
  125. + (UIViewController *)globalsEntryViewController:(FLEXGlobalsRow)row {
  126. FLEXLiveObjectsController *liveObjectsViewController = [self new];
  127. liveObjectsViewController.title = [self globalsEntryTitle:row];
  128. return liveObjectsViewController;
  129. }
  130. #pragma mark - Search bar
  131. - (void)updateSearchResults:(NSString *)filter {
  132. NSInteger selectedScope = self.selectedScope;
  133. if (filter.length) {
  134. NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", filter];
  135. self.filteredClassNames = [self.allClassNames filteredArrayUsingPredicate:searchPredicate];
  136. } else {
  137. self.filteredClassNames = self.allClassNames;
  138. }
  139. if (selectedScope == kFLEXLiveObjectsSortAlphabeticallyIndex) {
  140. self.filteredClassNames = [self.filteredClassNames sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
  141. } else if (selectedScope == kFLEXLiveObjectsSortByCountIndex) {
  142. self.filteredClassNames = [self.filteredClassNames sortedArrayUsingComparator:^NSComparisonResult(NSString *className1, NSString *className2) {
  143. NSNumber *count1 = self.instanceCountsForClassNames[className1];
  144. NSNumber *count2 = self.instanceCountsForClassNames[className2];
  145. // Reversed for descending counts.
  146. return [count2 compare:count1];
  147. }];
  148. } else if (selectedScope == kFLEXLiveObjectsSortBySizeIndex) {
  149. self.filteredClassNames = [self.filteredClassNames sortedArrayUsingComparator:^NSComparisonResult(NSString *className1, NSString *className2) {
  150. NSNumber *count1 = self.instanceCountsForClassNames[className1];
  151. NSNumber *count2 = self.instanceCountsForClassNames[className2];
  152. NSNumber *size1 = self.instanceSizesForClassNames[className1];
  153. NSNumber *size2 = self.instanceSizesForClassNames[className2];
  154. // Reversed for descending sizes.
  155. return [@(count2.integerValue * size2.integerValue) compare:@(count1.integerValue * size1.integerValue)];
  156. }];
  157. }
  158. [self updateHeaderTitle];
  159. [self.tableView reloadData];
  160. }
  161. #pragma mark - Table view data source
  162. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  163. return 1;
  164. }
  165. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  166. return self.filteredClassNames.count;
  167. }
  168. - (UITableViewCell *)tableView:(__kindof UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  169. UITableViewCell *cell = [tableView
  170. dequeueReusableCellWithIdentifier:kFLEXDefaultCell
  171. forIndexPath:indexPath
  172. ];
  173. NSString *className = self.filteredClassNames[indexPath.row];
  174. NSNumber *count = self.instanceCountsForClassNames[className];
  175. NSNumber *size = self.instanceSizesForClassNames[className];
  176. unsigned long totalSize = count.unsignedIntegerValue * size.unsignedIntegerValue;
  177. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  178. cell.textLabel.text = [NSString stringWithFormat:@"%@ (%ld, %@)",
  179. className, (long)[count integerValue],
  180. [NSByteCountFormatter
  181. stringFromByteCount:totalSize
  182. countStyle:NSByteCountFormatterCountStyleFile
  183. ]
  184. ];
  185. return cell;
  186. }
  187. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
  188. return self.headerTitle;
  189. }
  190. #pragma mark - Table view delegate
  191. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  192. NSString *className = self.filteredClassNames[indexPath.row];
  193. UIViewController *instances = [FLEXObjectListViewController instancesOfClassWithName:className];
  194. [self.navigationController pushViewController:instances animated:YES];
  195. }
  196. @end