On Wed, Aug 18, 2010 at 4:22 PM, Kyle Sluder <[email protected]> wrote: > On Wed, Aug 18, 2010 at 12:49 PM, Sherm Pendley <[email protected]> > wrote: >> The "[foo release]" is perfectly correct, but if >> -stringByReplacingOccurrencesOfString:withString: is implemented with >> a simple "return self;" then *both* foo and bar would be immediately >> released. Implementing it as "return [[self retain] autorelease]" >> prevents such problems. > > It doesn't violate the memory management guidelines to do so. The onus > is technically on the caller to retain bar if he wants to use it later.
Here's the example you snipped: NSString *foo = [[NSString alloc] initWithString:@"foo"]; NSString *bar = [foo stringByReplacingOccurrencesOfString:@"foo" withString:@"foo"]; [foo release]; The caller is doing nothing wrong here. It's finished using foo, and released it. If the caller's only use of bar is within the scope of the calling method, it's under no obligation to retain it. It's the responsibility of -stringByReplacing... to return an object that remains valid throughout the caller's scope, even if the original string is released. Doing "return [[self retain] autorelease]" fulfills that responsibility; "return self" does not. > See: > http://developer.apple.com/mac/library/documentation/cocoa/conceptual/MemoryMgmt/Articles/mmAccessorMethods.html Indeed, on that very page, at <http://developer.apple.com/mac/library/documentation/cocoa/conceptual/MemoryMgmt/Articles/mmAccessorMethods.html#//apple_ref/doc/uid/TP40003539-SW6>, it gives this example: - (NSString*) title { return [[title retain] autorelease]; } ... "Because the object returned from the get accessor is autoreleased in the current scope, it remains valid if the property value is changed. This makes the accessor more robust, but at the cost of additional overhead." Implementing -stringByReplacing... as "return [[self retain] autorelease];" makes the same guarantee, that the object returned by -stringByReplacing... will remain valid if the original string is released. sherm-- -- Cocoa programming in Perl: http://camelbones.sourceforge.net _______________________________________________ Cocoa-dev mailing list ([email protected]) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to [email protected]
