Ok, my bad - ARC does actually handle copied objects properly. I got wrong results because of using NSString for the test, because I wanted to use a class that already implemented copying instead of implementing it explicitly; when I repeated the test on a class inheriting from NSObject and implementing copyWithZone:
by returning [[Foo alloc] init]
, I got two "deallocated" messages. Thanks to @Paul.s for pointing that out.
is it allowed to call [obj copy] in ObjC with ARC?
-
30-07-2021 - |
Question
There's one thing I don't understand regarding ARC: how should we now treat local variables that were created using [... copy]
? If I make a property with (copy)
flag, ARC will handle this automatically, but as far as I know there's no __copy
flag for variables.
I've tested this with such code:
@interface Foo : NSString
@end
@implementation Foo
- (void) dealloc {
NSLog(@"%p deallocated", self);
}
- (NSUInteger) length {
return 1;
}
- (unichar) characterAtIndex: (NSUInteger) i {
return 'x';
}
@end
- (void) foo {
Foo *f = [[Foo alloc] init];
NSLog(@"%p", f);
Foo *f2 = [f copy];
NSLog(@"%p", f2);
}
What I get is:
0x102406530
0x102015f10
0x102406530 deallocated
I never get "0x102015f10 deallocated", which would suggest the copied variable doesn't get released. It doesn't even get autoreleased, because when I made another method [Foo foo]
that returned an autoreleased object, I did get a "deallocated" message a moment later.
So is there any way I can cause it to be released without converting it to a property?
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow