2012-09-13 31 views
1

我讀過很多關於SO的錯誤消息,但是沒有一個解決方案適用於我的情況。所以請在推薦其他帖子前閱讀代碼。提前致謝。NSMutableDictionary錯誤:發送給不可變對象的變異方法

我設置例外破發點,發現問題存在於[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; 
} 

回答

2

你的屬性定義返回原來的copy在所述屬性上使用吸氣劑時的對象。由於它是一個副本,所以你得到了不可變的對象。根據您使用的內存管理,嘗試更改copystrongretain

+0

@ Philip007請參閱[this](http://stackoverflow.com/q/816720/730701),瞭解如何處理可變對象作爲屬性。 – Adam

相關問題