NSMutableDictionary错误:将mutating方法发送到不可变对象

时间:2012-09-13 14:02:57

标签: objective-c

我在SO上阅读了很多关于相同错误消息的帖子,但这些解决方案都不适用于我的情况。所以请在推荐其他帖子之前阅读代码。提前谢谢。

我设置了异常断点,发现问题存在于[self.countryNameDictionary setObject:array forKey:initial];

在AppDelegate.h中

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (nonatomic,copy) NSMutableDictionary *countryNameDictionary;
@property (nonatomic,copy) NSMutableArray *countryNameInitials;
@end

在AppDelegate.m中

#import "AppDelegate.h"

@implementation AppDelegate     
@synthesize window = _window;
@synthesize countryNameDictionary = _countryNameDictionary;
@synthesize countryNameInitials = _countryNameInitials;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSMutableArray *permanentArray = [[NSMutableArray alloc]init];
    self.countryNameDictionary = [[NSMutableDictionary alloc]init];
    self.countryNameInitials = [[NSMutableArray alloc]init ];

    [[NSUserDefaults standardUserDefaults] setObject:@"YES" forKey:@"isFirstLaunch"];

    // run this code only once by creating and checking a user defaults key
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isFirstLaunch"] isEqualToString:@"YES"])
    {
        // locate and convert txt file to string
        NSString *path = [[NSBundle mainBundle] pathForResource:@"country_name" ofType:@"txt"];
        NSString *string = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

        // seperate string into array
        permanentArray = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]mutableCopy];
        // strip white space string
        permanentArray = [[permanentArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF != ''"]]mutableCopy];

        // enumerate a-z to set the two global variables
        for (int asciicode =65; asciicode<=90; asciicode++)
        {
            NSString *initial = [NSString stringWithFormat:@"%c",asciicode];
            self.countryNameInitials = [NSMutableArray arrayWithObject:initial];

            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[cd] %@",initial];
            NSMutableArray *array = [[permanentArray filteredArrayUsingPredicate:predicate]mutableCopy];

            // populate the dictionary with initial-country-names pair
            [self.countryNameDictionary setObject:array forKey:initial]; // PROBLEM IS HERE

            NSLog(@"self.countrynameDictionary is %@",self.countryNameInitials);
        }

        // set to a non-nil value
        [[NSUserDefaults standardUserDefaults] setObject:@"NO" forKey:@"isFirstLaunch"];
    }

    return YES;
}

1 个答案:

答案 0 :(得分:2)

在所述属性上使用getter时,属性定义返回原始对象的copy。因为它是一个副本,所以你得到了不可变对象。尝试将copy更改为strongretain,具体取决于您使用的内存管理。