You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否将对象驻留内存至应用退出?NSMutableDictionary内存留存时长问询

Hey there! Let's break down your questions about storing native contacts in an NSMutableDictionary and memory retention, step by step.

1. How to Store Native Contacts in NSMutableDictionary

First, let's walk through the implementation (we'll use the modern CNContactStore API since ABAddressBookRef is deprecated as of iOS 9):

  • Step 1: Request Contact Access Permission
    You need to ask the user for permission first. Add the NSContactsUsageDescription key to your Info.plist with a clear reason for needing access, then request permission:

    CNContactStore *store = [[CNContactStore alloc] init];
    [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            // Proceed to fetch contacts
            [self fetchContactsAndStoreInDictionary:store];
        } else {
            // Handle permission denial (e.g., show a prompt explaining why access is needed)
        }
    }];
    
  • Step 2: Fetch Contacts and Populate the Dictionary
    Define the contact fields you want to fetch, then retrieve contacts and store them in your NSMutableDictionary. We'll use the contact's unique identifier as the dictionary key for easy lookup:

    - (void)fetchContactsAndStoreInDictionary:(CNContactStore *)store {
        NSMutableDictionary *contactsDict = [[NSMutableDictionary alloc] init];
        NSArray *keysToFetch = @[CNContactIdentifierKey, CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
        CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
        
        NSError *error;
        BOOL success = [store enumerateContactsWithFetchRequest:request error:&error usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
            // Create a sub-dictionary to hold the contact's details
            NSMutableDictionary *contactDetails = [[NSMutableDictionary alloc] init];
            contactDetails[@"givenName"] = contact.givenName;
            contactDetails[@"familyName"] = contact.familyName;
            
            // Process and store phone numbers with their labels
            NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];
            for (CNLabeledValue *labeledValue in contact.phoneNumbers) {
                NSString *phoneNumber = labeledValue.value.stringValue;
                NSString *label = CNLabeledValue localizedStringForLabel:labeledValue.label;
                [phoneNumbers addObject:@{@"label": label, @"number": phoneNumber}];
            }
            contactDetails[@"phoneNumbers"] = phoneNumbers;
            
            // Add the contact to the main dictionary
            contactsDict[contact.identifier] = contactDetails;
        }];
        
        if (success) {
            // To keep this dictionary accessible long-term, assign it to a persistent strong reference
            [(AppDelegate *)[[UIApplication sharedApplication] delegate] setContactsDictionary:contactsDict];
        } else {
            NSLog(@"Error fetching contacts: %@", error.localizedDescription);
        }
    }
    
2. Can I Keep the Object in Memory Until the App Exits?

Absolutely! The key is maintaining a strong reference to your NSMutableDictionary. As long as there's at least one active strong reference pointing to it, ARC (Automatic Reference Counting) won't deallocate it.

For example:

  • Declare a property in your AppDelegate like @property (strong, nonatomic) NSMutableDictionary *contactsDictionary;
  • Assign your populated dictionary to this property (as shown in the code above)
  • This dictionary will stay in memory for the entire lifecycle of your app, until the app is terminated (by the user, system, or manual quit).
3. How Long Does an NSMutableDictionary Stay in Memory?

Its lifespan depends entirely on reference counting under ARC:

  • If the dictionary has active strong references (like being held by an AppDelegate property, a singleton instance, or a view controller that's still in the navigation stack), it will remain in memory.
  • Once all strong references to the dictionary are removed (e.g., you set the AppDelegate property to nil, or the view controller holding it is deallocated), ARC will automatically mark it for deallocation. It will be removed from memory the next time the system runs its cleanup cycle.

In short: If you keep a strong, persistent reference (like an app-level property), it'll stay until the app exits. Otherwise, it'll be cleaned up when no code is referencing it anymore.

内容的提问来源于stack exchange,提问作者Kapil_A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:27:48