Question

I'm teaching myself Objective-C 2.0 using Apple's Programming With Objective-C guide.

I have a question regarding what I believe to be implicitly created pointers.

If I were to rewrite the example code:

@implementation XYZShoutingPerson
- (void)saySomething:(NSString *)greeting {
    NSString *uppercaseGreeting = [greeting uppercaseString];
    [super saySomething:uppercaseGreeting];
}
@end

as

@implementation XYZShoutingPerson
- (void)saySomething:(NSString *)greeting {
    [super saySomething:[greeting uppercaseString]];
}
@end

would I be receiving an implicitly created pointer to a new NSString object and if so what would the scope of the pointer be?

Is one approach considered better than the other?

Was it helpful?

Solution

The rewritten code is essentially identical to the original. Yes you will receive a pointer from [greeting uppercaseString]. I suppose we could say its scope is the saySomething method. The string returned by uppercaseString will have a retain count of one and be autoreleased. In both the original code and your version, unless [super saySomething:] retains its argument (which is unlikely), the result of uppercaseString will be released and then deallocated when the current frame of the autorelease pool stack is popped. For practical purposes (unless you're managing your own autorelease pools) this means the result of uppercaseString will be deallocated at the end of the current turn of the event loop.

The compiler might be clever enough (especially if you're using ARC) to deallocate the result of uppercaseString as soon as [super saySomething:] returns. Again, this is the same in both versions of the code and the reason is that the result of uppercaseString is not used after [super saySomething:] returns.

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