FLEXLiveObjectsTableViewController.m 9.6 KB

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