Bravendary
Bravendary

Reputation: 113

Why is my NSmutableDictionary being turned into a NSCFString?

I have a dictionary allocated and ready to go in the appDelegate of my program.

//appdel.m
    NSMutableDictionary *dict;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions {    

    // Overide point for customization after application launch.

    dict = [[NSMutableDictionary alloc]init];


    dict = HBLoadDictionary(@"/dict.plist");

    // Add the tab bar controller's view to the window and display.
    [self.window addSubview:tabBarController.view];
    [self.window makeKeyAndVisible];

    return YES;
}

so I wanted this dictionary to exist in other files so I made it an external in other files to be edited and read from.

 //viewcontroller.m
    extern NSMutableDictionary *dict;

and later on I decide to set an object for a key. event is just an EKevent.

NSString* str = [[NSString alloc] initWithFormat:@"%@", event.eventIdentifier];
NSString *eID  = [[NSString alloc]init];
eID = [data valueForKey:@"id"];
[dict setObject:str forKey:eID];

when I make a call to the function I'll get this

-[NSCFString setObject:forKey:]: unrecognized selector sent to instance

At one point I even got a UIImage instead of a NSCFString which lead me to believe that memory is an issue and i'm not handling it right. Why is it even changing types like that? cause its causing function calls to mess up...

Upvotes: 0

Views: 870

Answers (1)

lazycs
lazycs

Reputation: 1604

The problem is that the NSMutableDictionary you allocated is immediately replaced by the return value from HBLoadDictionary. I would assume that HBLoadDictionary returns an autoreleased object, which you're not retaining anywhere. Shortly after you load the dictionary, it's deallocated so dict points to freed memory. Also, the first NSMutableDictionary that you allocated is leaked.

You can fix it by replacing

dict = [[NSMutableDictionary alloc]init];
dict = HBLoadDictionary(@"/dict.plist");

with

dict = [HBLoadDictionary(@"/dict.plist") retain];

As a side note, it's bad practice to initialize a global variable in an objective-c method. Although you probably won't have more than one application delegate, and its application:didFinishLaunchingWithOptions: method won't be called more than once, this could cause a memory leak in other situations. You're better off just having a class method that returns a static variable.

Upvotes: 2

Related Questions