2

I am learning Objective-C and iOS programming through the terrific iTunesU course posted by Stanford (http://www.stanford.edu/class/cs193p/cgi-bin/drupal/)

Assignment 2 is to create a calculator with variable buttons. The chain of commands (e.g. 3+x-y) is stored in a NSMutableArray as "anExpression", and then we sub in random values for x and y based on an NSDictionary to get a solution. This part of the assignment is tripping me up:

The final two [methods] “convert” anExpression to/from a property list:

 + (id)propertyListForExpression:(id)anExpression;
+ (id)expressionForPropertyList:(id)propertyList;

You’ll remember from lecture that a property list is just any combination of NSArray, NSDictionary, NSString, NSNumber, etc., so why do we even need this method since anExpression is already a property list? (Since the expressions we build are NSMutableArrays that contain only NSString and NSNumber objects, they are, indeed, already property lists.) Well, because the caller of our API has no idea that anExpression is a property list. That’s an internal implementation detail we have chosen not to expose to callers.

Even so, you may think, the implementation of these two methods is easy because anExpression is already a property list so we can just return the argument right back, right? Well, yes and no. The memory management on this one is a bit tricky. We’ll leave it up to you to figure out. Give it your best shot.

Obviously, I am missing something with respect to memory management because I don't see why I can't just return the passed arguments right back.

Thanks in advance for any answers!

1 Answer 1

4

Consider what happens if you do this:

NSArray *somePropertyList = [[NSArray alloc] initWithContentsOfFile:@"..."];
id otherPropertyList = [SomeClass propertyListForExpression:somePropertyList];
[somePropertyList release];

// 'somePropertyList' has been destroyed...
// is 'otherPropertyList' valid at this point?
[otherPropertyList writeToFile:@"..." atomically:YES];

The typical Objective-C pattern, therefore, is to retain and autorelease, so the caller still doesn't have to manage the memory, but so the object doesn't get destroyed too early:

+ (id)propertyListForExpression:(id)expr {
    // increments the retain count by 1
    // then sets it up to be decremented at some point in the future
    // (thus balancing it out, and the caller doesn't have to do anything)
    return [[expr retain] autorelease];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.