### Define resource filenames Source: https://github.com/tinymind/lsunusedresources/blob/master/README.md Example list of image resource files that may be referenced dynamically in code. ```text icon_tag_0.png icon_tag_1.png icon_tag_2.png icon_tag_3.png icon_title-0.png icon_title-1.png icon_title-2.png icon_test0.png icon_test1.png icon_test2.png ``` -------------------------------- ### Initialize and Use ResourceStringSearcher Source: https://context7.com/tinymind/lsunusedresources/llms.txt Initialize the ResourceStringSearcher singleton, create default resource patterns, and start a search. Listen for completion notifications and check for resource usage. ```objectivec #import "ResourceStringSearcher.h" ResourceStringSearcher *stringSearcher = [ResourceStringSearcher sharedObject]; // Create default patterns for common file types NSArray *resourceSuffixs = @[@"png", @"jpg", @"gif"]; NSArray *patterns = [stringSearcher createDefaultResourcePatternsWithResourceSuffixs:resourceSuffixs]; // Default patterns include: // .h/.c/.cpp: ([a-zA-Z0-9_-]*)\.(png|gif|jpg) // .m/.mm: @"(.*?)" // .swift: "(.*?)" // .xib/.storyboard: image name=\"(.+?)\" // .strings: =\s*\"(.*)\"\s*; // .html: img\s+src=[\"'](.*?)['"] // .js: ["']src["'],\s+["'](.*?)["'] // .json: :\s*\"(.*?)\" // .plist: >(.*?)< // Start searching for string references [stringSearcher startWithProjectPath:@"/Users/dev/MyProject" excludeFolders:@[@"Pods"] resourceSuffixs:resourceSuffixs resourcePatterns:patterns]; // Listen for completion [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onStringSearchDone:) name:kNotificationResourceStringQueryDone object:nil]; - (void)onStringSearchDone:(NSNotification *)notification { // Check if a resource name exists in the codebase BOOL isUsed = [stringSearcher containsResourceName:@"icon_home"]; // Check for similar names (handles dynamic string concatenation) // e.g., "icon_tag_1" matches if code contains "icon_tag_%d" or "icon_tag_" BOOL hasSimilar = [stringSearcher containsSimilarResourceName:@"icon_tag_1"]; // Access all found string references NSSet *allStrings = stringSearcher.resStringSet; NSLog(@"Found %lu string references", allStrings.count); } // Reset for new search [stringSearcher reset]; ``` -------------------------------- ### Reference resources dynamically in Objective-C Source: https://github.com/tinymind/lsunusedresources/blob/master/README.md Examples of how resources can be accessed using string concatenation, which the tool can be configured to ignore during unused resource scanning. ```objc NSInteger index = random() % 4; UIImage *img0 = [UIImage imageNamed:[NSString stringWithFormat:@"icon_tag_%d", index]]; // Or UIImage *img1 = [self createImageWithPrefix:@"icon_title" concat:@"-" andIndex:index]; // Or UIImage *img2 = [self createImageWithPrefix:@"icon_test" andIndex:index]; ``` -------------------------------- ### Implement UnusedResourceDetector in Objective-C Source: https://context7.com/tinymind/lsunusedresources/llms.txt This class coordinates file and string searches to identify unused resources. It requires setting up project paths and exclusion folders before starting the search. ```objectivec #import "ResourceFileSearcher.h" #import "ResourceStringSearcher.h" #import "ResourceSettings.h" #import "StringUtils.h" @interface UnusedResourceDetector : NSObject @property (nonatomic, assign) BOOL isFileDone; @property (nonatomic, assign) BOOL isStringDone; @property (nonatomic, strong) NSMutableArray *unusedResources; @end @implementation UnusedResourceDetector - (void)startSearchWithProjectPath:(NSString *)projectPath { // Configure settings ResourceSettings *settings = [ResourceSettings sharedObject]; settings.projectPath = projectPath; settings.excludeFolders = @[@"Pods", @"Carthage", @"build"]; settings.resourceSuffixs = @[@"imageset", @"png", @"jpg", @"gif"]; settings.matchSimilarName = @(YES); // Ignore dynamically referenced resources // Reset previous search state [[ResourceFileSearcher sharedObject] reset]; [[ResourceStringSearcher sharedObject] reset]; self.unusedResources = [NSMutableArray array]; self.isFileDone = NO; self.isStringDone = NO; // Register for completion notifications [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onFileSearchDone:) name:kNotificationResourceFileQueryDone object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onStringSearchDone:) name:kNotificationResourceStringQueryDone object:nil]; // Create search patterns for all file types NSArray *patterns = [[ResourceStringSearcher sharedObject] createDefaultResourcePatternsWithResourceSuffixs:settings.resourceSuffixs]; settings.resourcePatterns = patterns; // Start parallel searches [[ResourceFileSearcher sharedObject] startWithProjectPath:projectPath excludeFolders:settings.excludeFolders resourceSuffixs:settings.resourceSuffixs]; [[ResourceStringSearcher sharedObject] startWithProjectPath:projectPath excludeFolders:settings.excludeFolders resourceSuffixs:settings.resourceSuffixs resourcePatterns:patterns]; } - (void)onFileSearchDone:(NSNotification *)notification { self.isFileDone = YES; [self analyzeResultsIfReady]; } - (void)onStringSearchDone:(NSNotification *)notification { self.isStringDone = YES; [self analyzeResultsIfReady]; } - (void)analyzeResultsIfReady { if (!self.isFileDone || !self.isStringDone) return; ResourceFileSearcher *fileSearcher = [ResourceFileSearcher sharedObject]; ResourceStringSearcher *stringSearcher = [ResourceStringSearcher sharedObject]; ResourceSettings *settings = [ResourceSettings sharedObject]; // Compare resources against string references for (NSString *resourceName in fileSearcher.resNameInfoDict) { // Check if resource name appears in any source file if (![stringSearcher containsResourceName:resourceName]) { // If similar name matching is enabled, check for dynamic references if (!settings.matchSimilarName.boolValue || ![stringSearcher containsSimilarResourceName:resourceName]) { ResourceFileInfo *info = fileSearcher.resNameInfoDict[resourceName]; [self.unusedResources addObject:info]; } } } // Report results uint64_t totalSize = 0; for (ResourceFileInfo *info in self.unusedResources) { totalSize += info.fileSize; NSLog(@"Unused: %@ (%.2f KB) at %@", info.name, info.fileSize / 1024.0, info.path); } NSLog(@"Total unused resources: %lu", self.unusedResources.count); NSLog(@"Total wasted space: %.2f KB", totalSize / 1024.0); } @end // Usage UnusedResourceDetector *detector = [[UnusedResourceDetector alloc] init]; [detector startSearchWithProjectPath:@"/Users/dev/MyiOSProject"]; ``` -------------------------------- ### Get File Size by Path Source: https://context7.com/tinymind/lsunusedresources/llms.txt Use `fileSizeAtPath:isDir:` to get the size of a file or directory at a given path. For directories, it recursively calculates the total size of all contents. The `isDir` output parameter indicates if the path points to a directory. ```Objective-C #import "FileUtils.h" // Get file size with directory detection BOOL isDirectory = NO; uint64_t fileSize = [FileUtils fileSizeAtPath:@"/path/to/icon.png" isDir:&isDirectory]; // fileSize = 45056 (bytes), isDirectory = NO // For directories, automatically calculates total size of all contents uint64_t imagesetSize = [FileUtils fileSizeAtPath:@"/path/to/Assets.xcassets/logo.imageset" isDir:&isDirectory]; // imagesetSize = 125440 (total bytes of all files in imageset), isDirectory = YES ``` -------------------------------- ### Configure ResourceSettings Source: https://context7.com/tinymind/lsunusedresources/llms.txt Manage user preferences for resource searching, including project path, excluded folders, resource suffixes, search patterns, and similar name matching. ```objectivec #import "ResourceSettings.h" ResourceSettings *settings = [ResourceSettings sharedObject]; // Configure project path settings.projectPath = @"/Users/dev/MyProject"; // Set folders to exclude from search settings.excludeFolders = @[@"Pods", @"Carthage", @"build", @"DerivedData"]; // Configure resource file extensions to search for settings.resourceSuffixs = @[@"imageset", @"png", @"jpg", @"gif", @"pdf"]; // Enable similar name matching (for dynamically referenced resources) settings.matchSimilarName = @(YES); // Manage search patterns NSArray *currentPatterns = settings.resourcePatterns; // Update a pattern at specific index [settings updateResourcePatternAtIndex:0 withObject:@"swift" forKey:@"PatternSuffix"]; // Add a new custom pattern NSDictionary *newPattern = @{ @"PatternEnable": @(YES), @"PatternSuffix": @"vue", @"PatternRegex": @"src=['"](.+?)['"]", @"PatternGroupIndex": @(1) }; [settings addResourcePattern:newPattern]; // Remove a pattern [settings removeResourcePatternAtIndex:2]; // All settings are automatically persisted to NSUserDefaults ``` -------------------------------- ### Display Formatted File Size Source: https://context7.com/tinymind/lsunusedresources/llms.txt Demonstrates how to format file and folder sizes into human-readable units like KB and MB using standard Objective-C NSLog. ```Objective-C // Display formatted size NSLog(@"File size: %.2f KB", fileSize / 1024.0); NSLog(@"Folder size: %.2f MB", folderSize / (1024.0 * 1024.0)); ``` -------------------------------- ### Create and Use Custom ResourceStringPattern Source: https://context7.com/tinymind/lsunusedresources/llms.txt Define custom resource extraction patterns for specific file types using a dictionary. Initialize a ResourceStringPattern object and access its properties. ```objectivec #import "ResourceStringSearcher.h" // Create a custom pattern for a file type NSDictionary *customPattern = @{ @"PatternEnable": @(YES), // Enable/disable this pattern @"PatternSuffix": @"jsx", // File extension to match @"PatternRegex": @"require\(['"](.+?)['"]\)", // Regex pattern @"PatternGroupIndex": @(1) // Capture group index for resource name }; // Initialize a ResourceStringPattern from dictionary ResourceStringPattern *pattern = [[ResourceStringPattern alloc] initWithDictionary:customPattern]; // Pattern properties NSLog(@"Suffix: %@", pattern.suffix); // "jsx" NSLog(@"Enabled: %@", pattern.enable ? @"YES" : @"NO"); // "YES" NSLog(@"Regex: %@", pattern.regex); // "require\(['"](.+?)['"]\)" NSLog(@"Group Index: %ld", pattern.groupIndex); // 1 // Create an empty pattern template for UI NSDictionary *emptyPattern = [[ResourceStringSearcher sharedObject] createEmptyResourcePattern]; // Returns: @{@"PatternEnable": @1, @"PatternSuffix": @"tmp", @"PatternRegex": @"(.+)", @"PatternGroupIndex": @1} ``` -------------------------------- ### FileUtils - File and Folder Size Calculation Source: https://context7.com/tinymind/lsunusedresources/llms.txt Provides methods for calculating the size of files and directories, useful for managing storage and identifying large resources. ```APIDOC ## FileUtils ### Description The `FileUtils` utility class provides methods for calculating file and folder sizes, essential for displaying the total size of unused resources and helping developers prioritize which resources to remove. ### Methods #### `fileSizeAtPath:isDir:` - **Description**: Gets the size of a file or directory at the specified path. For directories, it calculates the total size of all contents. - **Parameters**: - `path` (NSString) - The path to the file or directory. - `isDir` (BOOL *) - A pointer to a BOOL that will be set to YES if the path is a directory, NO otherwise. - **Returns**: (uint64_t) - The size of the file or directory in bytes. #### `folderSizeAtPath:` - **Description**: Calculates the total size of all files within a given folder path recursively. - **Parameters**: - `path` (NSString) - The path to the folder. - **Returns**: (uint64_t) - The total size of the folder in bytes. ### Example Usage ```objectivec #import "FileUtils.h" // Get file size with directory detection BOOL isDirectory = NO; uint64_t fileSize = [FileUtils fileSizeAtPath:@"/path/to/icon.png" isDir:&isDirectory]; // fileSize = 45056 (bytes), isDirectory = NO // For directories, automatically calculates total size of all contents uint64_t imagesetSize = [FileUtils fileSizeAtPath:@"/path/to/Assets.xcassets/logo.imageset" isDir:&isDirectory]; // imagesetSize = 125440 (total bytes of all files in imageset), isDirectory = YES // Calculate folder size directly uint64_t folderSize = [FileUtils folderSizeAtPath:@"/path/to/Assets.xcassets"]; // Returns total size of all files recursively // Display formatted size NSLog(@"File size: %.2f KB", fileSize / 1024.0); NSLog(@"Folder size: %.2f MB", folderSize / (1024.0 * 1024.0)); ``` ``` -------------------------------- ### Scan Project Resources with ResourceFileSearcher Source: https://context7.com/tinymind/lsunusedresources/llms.txt Use the ResourceFileSearcher singleton to initiate a project scan, handle completion via notifications, and access the resulting resource dictionary. ```objectivec #import "ResourceFileSearcher.h" // Access the shared singleton instance ResourceFileSearcher *searcher = [ResourceFileSearcher sharedObject]; // Start scanning a project directory for resource files // Parameters: // - projectPath: Root path of the Xcode project // - excludeFolders: Array of folder names to skip (e.g., @[@"Pods", @"Carthage"]) // - resourceSuffixs: File extensions to search for (e.g., @[@"imageset", @"png", @"jpg", @"gif"]) [searcher startWithProjectPath:@"/Users/dev/MyProject" excludeFolders:@[@"Pods", @"build", @"DerivedData"] resourceSuffixs:@[@"imageset", @"jpg", @"gif", @"png"]]; // Listen for completion notification [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResourceFileQueryDone:) name:kNotificationResourceFileQueryDone object:nil]; // Access results after completion - (void)onResourceFileQueryDone:(NSNotification *)notification { NSDictionary *results = searcher.resNameInfoDict; // results = { @"icon_home": ResourceFileInfo, @"background": ResourceFileInfo, ... } for (NSString *resourceName in results) { ResourceFileInfo *info = results[resourceName]; NSLog(@"Found: %@ at %@ (%.2f KB)", info.name, info.path, info.fileSize / 1024.0); } } // Reset the searcher for a new search [searcher reset]; // Check if a folder is an imageset container BOOL isImageSet = [searcher isImageSetFolder:@"AppIcon.appiconset"]; // YES ``` -------------------------------- ### Access Resource Metadata with ResourceFileInfo Source: https://context7.com/tinymind/lsunusedresources/llms.txt ResourceFileInfo objects are generated during the scan process and provide access to file properties and preview images. ```objectivec #import "ResourceFileSearcher.h" // ResourceFileInfo is automatically created during file scanning // Properties available: @interface ResourceFileInfo : NSObject @property (strong, nonatomic) NSString *name; // File/folder name (e.g., "icon_home.png") @property (strong, nonatomic) NSString *path; // Full path to the resource @property (assign, nonatomic) BOOL isDir; // YES if this is a directory (e.g., .imageset) @property (assign, nonatomic) uint64_t fileSize; // Size in bytes - (NSImage *)image; // Returns preview image for display @end // Example usage after search completes ResourceFileInfo *info = [ResourceFileSearcher sharedObject].resNameInfoDict[@"app_logo"]; NSLog(@"Resource: %@", info.name); // "app_logo.imageset" NSLog(@"Path: %@", info.path); // "/Users/dev/MyApp/Assets.xcassets/app_logo.imageset" NSLog(@"Is Directory: %@", info.isDir ? @"YES" : @"NO"); // "YES" NSLog(@"Size: %.2f KB", info.fileSize / 1024.0); // "45.32 KB" // Get preview image for UI display NSImage *preview = [info image]; // Loads first image from imageset if directory ``` -------------------------------- ### ResourceFileInfo Model Source: https://context7.com/tinymind/lsunusedresources/llms.txt The ResourceFileInfo class encapsulates metadata for discovered resource files, including path, size, and preview capabilities. ```APIDOC ## ResourceFileInfo ### Description Model class representing a discovered resource file or directory within the project. ### Properties - **name** (NSString): The file or folder name. - **path** (NSString): The full absolute path to the resource. - **isDir** (BOOL): Indicates if the resource is a directory (e.g., .imageset). - **fileSize** (uint64_t): The size of the resource in bytes. ### Methods - **image**(): Returns an NSImage preview for the resource. ``` -------------------------------- ### ResourceFileSearcher API Source: https://context7.com/tinymind/lsunusedresources/llms.txt The ResourceFileSearcher singleton manages the scanning of project directories to locate resource files based on specified suffixes and exclusion rules. ```APIDOC ## ResourceFileSearcher ### Description Singleton class responsible for scanning project directories to locate all resource files and mapping them to their metadata. ### Methods - **sharedObject**(): Returns the singleton instance. - **startWithProjectPath:excludeFolders:resourceSuffixs:**(NSString *projectPath, NSArray *excludeFolders, NSArray *resourceSuffixs): Starts the scanning process. - **reset**(): Resets the searcher state for a new search. - **isImageSetFolder:**(NSString *folderName): Checks if a folder is an imageset container. ### Notifications - **kNotificationResourceFileQueryDone**: Posted when the file scanning process is complete. ### Properties - **resNameInfoDict** (NSDictionary): Dictionary mapping resource names to ResourceFileInfo objects. ``` -------------------------------- ### Calculate Folder Size Source: https://context7.com/tinymind/lsunusedresources/llms.txt Use `folderSizeAtPath:` to calculate the total size of all files within a specified directory recursively. This is useful for determining the overall disk space occupied by a folder. ```Objective-C // Calculate folder size directly uint64_t folderSize = [FileUtils folderSizeAtPath:@"/path/to/Assets.xcassets"]; // Returns total size of all files recursively ``` -------------------------------- ### Remove Resource Suffixes and Extensions Source: https://context7.com/tinymind/lsunusedresources/llms.txt Use `stringByRemoveResourceSuffix:` to strip file extensions and retina suffixes (@2x, @3x) from resource names. Optionally, specify a suffix to remove only that specific suffix along with the extension. ```Objective-C #import "StringUtils.h" // Remove file extension and retina suffixes from resource name NSString *normalized = [StringUtils stringByRemoveResourceSuffix:@"icon_home@2x.png"]; // Result: "icon_home" NSString *normalized2 = [StringUtils stringByRemoveResourceSuffix:@"background@3x.jpg"]; // Result: "background" // Remove only specific suffix NSString *partial = [StringUtils stringByRemoveResourceSuffix:@"logo@2x.png" suffix:@"png"]; // Result: "logo" (removes .png and @2x) ``` -------------------------------- ### StringUtils - Resource Name Processing Source: https://context7.com/tinymind/lsunusedresources/llms.txt Provides methods to normalize resource file names by removing extensions and retina suffixes, and to check if a file is an image type. ```APIDOC ## StringUtils ### Description The `StringUtils` utility class provides helper methods for processing resource file names, including removing file extensions, stripping retina suffixes (@2x, @3x), and identifying image file types. ### Methods #### `stringByRemoveResourceSuffix:` - **Description**: Removes file extension and retina suffixes (e.g., @2x, @3x) from a resource name. - **Parameters**: - `resourceName` (NSString) - The input resource name. - **Returns**: (NSString) - The normalized resource name. #### `stringByRemoveResourceSuffix:suffix:` - **Description**: Removes a specific suffix (including file extension) from a resource name. - **Parameters**: - `resourceName` (NSString) - The input resource name. - `suffix` (NSString) - The specific suffix to remove (e.g., "png"). - **Returns**: (NSString) - The resource name with the specified suffix removed. #### `isImageTypeWithName:` - **Description**: Checks if a given file name corresponds to a supported image type. - **Parameters**: - `fileName` (NSString) - The name of the file to check. - **Returns**: (BOOL) - YES if the file is a supported image type, NO otherwise. ### Supported Image Types png, jpg, jpeg, gif, bmp, pdf ### Example Usage ```objectivec // Remove file extension and retina suffixes from resource name NSString *normalized = [StringUtils stringByRemoveResourceSuffix:@"icon_home@2x.png"]; // Result: "icon_home" NSString *normalized2 = [StringUtils stringByRemoveResourceSuffix:@"background@3x.jpg"]; // Result: "background" // Remove only specific suffix NSString *partial = [StringUtils stringByRemoveResourceSuffix:@"logo@2x.png" suffix:@"png"]; // Result: "logo" // Check if a file is an image type BOOL isImage1 = [StringUtils isImageTypeWithName:@"icon.png"]; // YES BOOL isImage2 = [StringUtils isImageTypeWithName:@"icon.jpg"]; // YES BOOL isImage3 = [StringUtils isImageTypeWithName:@"icon.jpeg"]; // YES BOOL isImage4 = [StringUtils isImageTypeWithName:@"icon.gif"]; // YES BOOL isImage5 = [StringUtils isImageTypeWithName:@"icon.pdf"]; // YES BOOL isImage6 = [StringUtils isImageTypeWithName:@"data.json"]; // NO ``` ``` -------------------------------- ### Check if File is Image Type Source: https://context7.com/tinymind/lsunusedresources/llms.txt Use `isImageTypeWithName:` to determine if a given file name corresponds to a supported image type. Supported types include png, jpg, jpeg, gif, bmp, and pdf. ```Objective-C // Check if a file is an image type BOOL isImage1 = [StringUtils isImageTypeWithName:@"icon.png"]; // YES BOOL isImage2 = [StringUtils isImageTypeWithName:@"icon.jpg"]; // YES BOOL isImage3 = [StringUtils isImageTypeWithName:@"icon.jpeg"]; // YES BOOL isImage4 = [StringUtils isImageTypeWithName:@"icon.gif"]; // YES BOOL isImage5 = [StringUtils isImageTypeWithName:@"icon.pdf"]; // YES BOOL isImage6 = [StringUtils isImageTypeWithName:@"data.json"]; // NO // Supported image types: png, jpg, jpeg, gif, bmp, pdf ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.