Question

I'm trying to initialize a dict variable but I don't understand why one way works, while the other does not.

In case 1 everything is alright and I can use dict later.
In case 2 it will be released very soon (It will becomes a zombie) and If I try to use it later (outside a block) the program crashes.

Here's some code from my class (c++ mixed with objective-c) written for ios.
Inside the block i tried to initialize variable dict in two different ways.

class Data
{
public:
    NSMutableDictionary *dict;

    void DoSomeStuff()
    {
    [NSSomeFrameworkTool doSomeStuffWithCompletionHandler:^(NSError *err) {
        // case 1 - OK
        dict = [[NSMutableDictionary alloc] initWithDictionary:[NSKeyedUnarchiver unarchiveObjectWithFile:@"dict.dat"]];

        // case 2 - will crash later if i try to use dict
        dict = [NSKeyedUnarchiver unarchiveObjectWithFile:@"dict.dat"];   }];
    }
}

This class has class variable dict, which is initialized in the DoSomeStuff() method.
That method calls a method from the ios framework that uses block (as a callback) to inform me that some task is done.

I was wondering why case 1 and case 2 work different. Maybe it is forbidden to use references outside the block, that was initialized inside this block?
What's wrong with doing this the way shown in case2?

Was it helpful?

Solution

In first case you don't release your dict, and in second case it is autoreleased so you should retain it.

dict = [[NSKeyedUnarchiver unarchiveObjectWithFile:@"dict.dat"] retain];

OTHER TIPS

I think you can use a block variable here.

__block NSMutableDictionary *dict;

Variables are immutable inside of the block. They are a constant copy, a snapshot of the variable at the time of "block creation" so it can not be modified inside the block. The block variable will move the variable to the 'Heap' from the 'Stack' allowing you to change it's state. I'm by no means an expert on blocks, being that they are relatively new to Objective c.But there are some good articles if you google around to learn from.

http://pragmaticstudio.com/blog/2010/7/28/ios4-blocks-1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top