FLEXLiveObjectsTableViewController.m 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 "FLEXInstancesTableViewController.h"
  11. #import "FLEXUtility.h"
  12. #import "FLEXScopeCarousel.h"
  13. #import <objc/runtime.h>
  14. static const NSInteger kFLEXLiveObjectsSortAlphabeticallyIndex = 0;
  15. static const NSInteger kFLEXLiveObjectsSortByCountIndex = 1;
  16. static const NSInteger kFLEXLiveObjectsSortBySizeIndex = 2;
  17. @interface FLEXLiveObjectsTableViewController ()
  18. @property (nonatomic) NSDictionary<NSString *, NSNumber *> *instanceCountsForClassNames;
  19. @property (nonatomic) NSDictionary<NSString *, NSNumber *> *instanceSizesForClassNames;
  20. @property (nonatomic, readonly) NSArray<NSString *> *allClassNames;
  21. @property (nonatomic) NSArray<NSString *> *filteredClassNames;
  22. @end
  23. @implementation FLEXLiveObjectsTableViewController
  24. - (void)viewDidLoad
  25. {
  26. [super viewDidLoad];
  27. self.showsSearchBar = YES;
  28. self.searchBarDebounceInterval = kFLEXDebounceInstant;
  29. self.showsCarousel = YES;
  30. self.carousel.items = @[@"A→Z", @"Count", @"Size"];
  31. self.refreshControl = [UIRefreshControl new];
  32. [self.refreshControl addTarget:self action:@selector(refreshControlDidRefresh:) forControlEvents:UIControlEventValueChanged];
  33. [self reloadTableData];
  34. }
  35. - (NSArray<NSString *> *)allClassNames
  36. {
  37. return self.instanceCountsForClassNames.allKeys;
  38. }
  39. - (void)reloadTableData
  40. {
  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 dictionary];
  61. NSMutableDictionary<NSString *, NSNumber *> *mutableSizesForClassNames = [NSMutableDictionary dictionary];
  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. {
  78. [self reloadTableData];
  79. [self.refreshControl endRefreshing];
  80. }
  81. - (void)updateTitle
  82. {
  83. NSString *title = @"Live Objects";
  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. title = [title stringByAppendingFormat:@" (%lu, %@)", (unsigned long)totalCount,
  101. [NSByteCountFormatter stringFromByteCount:totalSize countStyle:NSByteCountFormatterCountStyleFile]];
  102. } else {
  103. title = [title stringByAppendingFormat:@" (filtered, %lu, %@)", (unsigned long)filteredCount,
  104. [NSByteCountFormatter stringFromByteCount:filteredSize countStyle:NSByteCountFormatterCountStyleFile]];
  105. }
  106. self.title = title;
  107. }
  108. #pragma mark - FLEXGlobalsEntry
  109. + (NSString *)globalsEntryTitle:(FLEXGlobalsRow)row {
  110. return @"💩 Heap Objects";
  111. }
  112. + (UIViewController *)globalsEntryViewController:(FLEXGlobalsRow)row {
  113. return [self new];
  114. }
  115. #pragma mark - Search bar
  116. - (void)updateSearchResults:(NSString *)filter
  117. {
  118. NSInteger selectedScope = self.selectedScope;
  119. if (filter.length) {
  120. NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", filter];
  121. self.filteredClassNames = [self.allClassNames filteredArrayUsingPredicate:searchPredicate];
  122. } else {
  123. self.filteredClassNames = self.allClassNames;
  124. }
  125. if (selectedScope == kFLEXLiveObjectsSortAlphabeticallyIndex) {
  126. self.filteredClassNames = [self.filteredClassNames sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
  127. } else if (selectedScope == kFLEXLiveObjectsSortByCountIndex) {
  128. self.filteredClassNames = [self.filteredClassNames sortedArrayUsingComparator:^NSComparisonResult(NSString *className1, NSString *className2) {
  129. NSNumber *count1 = self.instanceCountsForClassNames[className1];
  130. NSNumber *count2 = self.instanceCountsForClassNames[className2];
  131. // Reversed for descending counts.
  132. return [count2 compare:count1];
  133. }];
  134. } else if (selectedScope == kFLEXLiveObjectsSortBySizeIndex) {
  135. self.filteredClassNames = [self.filteredClassNames sortedArrayUsingComparator:^NSComparisonResult(NSString *className1, NSString *className2) {
  136. NSNumber *count1 = self.instanceCountsForClassNames[className1];
  137. NSNumber *count2 = self.instanceCountsForClassNames[className2];
  138. NSNumber *size1 = self.instanceSizesForClassNames[className1];
  139. NSNumber *size2 = self.instanceSizesForClassNames[className2];
  140. // Reversed for descending sizes.
  141. return [@(count2.integerValue * size2.integerValue) compare:@(count1.integerValue * size1.integerValue)];
  142. }];
  143. }
  144. [self updateTitle];
  145. [self.tableView reloadData];
  146. }
  147. #pragma mark - Table view data source
  148. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  149. {
  150. return 1;
  151. }
  152. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  153. {
  154. return self.filteredClassNames.count;
  155. }
  156. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  157. {
  158. static NSString *CellIdentifier = @"Cell";
  159. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  160. if (!cell) {
  161. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
  162. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  163. cell.textLabel.font = [FLEXUtility defaultTableViewCellLabelFont];
  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.textLabel.text = [NSString stringWithFormat:@"%@ (%ld, %@)", className, (long)[count integerValue],
  170. [NSByteCountFormatter stringFromByteCount:totalSize countStyle:NSByteCountFormatterCountStyleFile]];
  171. return cell;
  172. }
  173. #pragma mark - Table view delegate
  174. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  175. {
  176. NSString *className = self.filteredClassNames[indexPath.row];
  177. FLEXInstancesTableViewController *instancesViewController = [FLEXInstancesTableViewController instancesTableViewControllerForClassName:className];
  178. [self.navigationController pushViewController:instancesViewController animated:YES];
  179. }
  180. @end