A bit confused here


At the bottom of page 288, you are presenting some sample code in reference to extracting a string and attributes for a NSAttributedString from a RTF file.

The code is as follows: NSDictionary *myDict; NSData *data = [NSData dataWithContentsOfFile:@"myfile.rtf"]; NSAttributedString *aString; aString = [[NSAttributedString alloc] initWithRTF:data documentAttributes:&myDict];
What I don’t understand is when did “myDict” get the attributes to supply for the final assignment method to “aString”? Reading the documentation is a bit confusing also, but may indicate that the dictionary is set in the init method along with the new string. Is this possible? And if so, isn’t myDict pointing to nil right now? :confused:


myDict is being set by the call to -initWithRTF:documentAttributes:. We know this because myDict is being passed with the address-of (&) operator. So when we pass &myDict as a parameter, we are passing it a pointer to a pointer to an NSDictionary. In this case -initWithRTF:documentAttributes: sets that pointer to a new NSDictionary that it creates. That object is retain-autoreleased.

We see this used whenever an Objective-C method needs to return more than one item. Since a method can only “return” one value, it must use its arguments to pass back any additional values. Here’s a sketch of how that method might be implemented:

- (id)initWithRTF:(NSData *)data documentAttributes:(NSDictionary **)dictionaryOut
    self = [super init];
    if (self) {
        // do some stuff with 'data'
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:...];
        if (dictionaryOut)
            *dictionaryOut = dict;
    return self;



Thanks for the response and your code snippet makes it clear how a nonexistent (yet) dictionary can not only get things assigned to it but also gains its address, since it was (on the way in) pointing to NULL.