Re: Understanding ARC
Re: Understanding ARC
- Subject: Re: Understanding ARC
- From: Jim Geist <email@hidden>
- Date: Sat, 24 May 2014 14:56:17 -0700
The compiler handles the case of a returned object properly. Ownership in the form of one reference will pass, in your example, from returnString to testString due to the assignment to the return value. testString will be released when the block it’s in exits, and since there are no more referrers to the NSString at that point, it will be cleaned up.
Also, it is not generally needed to manage autorelease pools yourself unless you’re doing something more complicated. In the case of a Cocoa app, you will always be in the context of an autorelease pool during any call into your code from the run loop.
On May 24, 2014, at 2:34 PM, Jamie Ojomoh <email@hidden> wrote:
> Dear Sir,
>
> I'm trying to teach myself Objective C and I don't understand ARC very
> well. Please could someone help me.
>
> If I've understood this correctly (silly example):
>
> -(NSString*)stringdoodad
> {
> NSMutableString* returnString = [[NSMutableString alloc] init];
> @autoreleasepool
> {
> for (NSUInteger i = 0; i < 10; i++)
> {
> NSString* testString = @"hello";
> [returnString appendString:testString];
> }
> }
> return returnString;
> }
>
> In the example, everything inside the autoreleasepool block will be
> released as soon as the block ends, so it's necessary to declare the return
> value outside the block.
>
> When does returnString get released? Does it get automatically released as
> soon as the method ends and the value has been passed into whatever
> container was waiting for it? Do I need to do anything special in order to
> make sure that it is released as soon as it's done its job?
>
> If it gets called by the following method:
>
> -(void)stringDoodadCaller
> {
> @autoreleasepool
> {
> NSString* testString = [self stringdoodad];
> }
> }
>
> Would returnString be released because stringdoodad is called within an
> autoreleasepool?
>
> I don't think I've understood Apple's documentation on this - have I got
> this right or wrong?
>
> Also, why is it that memory automatically gets released properly when an
> application quits, but when a class is released any memory that hasn't been
> freed or released properly hangs around forever?
>
> Yours faithfully,
>
> Jamie Ojomoh
> _______________________________________________
>
> Cocoa-dev mailing list (email@hidden)
>
> 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:
>
> This email sent to email@hidden
_______________________________________________
Cocoa-dev mailing list (email@hidden)
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:
This email sent to email@hidden