FLEXLiveObjectsTableViewController.m 9.5 KB

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