I wrote a very basic class to play with the new ARC and accessor methods, just to get a feel for how they work. From what I've read, the ARC should replace manual reference counting, right? But I get a problem with my accessor methods.
Here's my Interface/Implementation for my Container
class:
// interface
@interface Container : NSObject {
NSMutableString *string;
}
- (NSMutableString *)string;
- (void)setString:(NSMutableString *)aString;
@end
// implementation
@implementation Container
- (NSMutableString *)string
{
return string;
}
- (void)setString:(NSMutableString *)aString
{
string = aString;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"inner string = %@", string];
}
@end
It seems alright to me, all the reference counting details are handled by the ARC I believe. The problem occurs in the main method:
Container *myContainer = [[Container alloc] init];
NSMutableString *aString = [NSMutableString stringWithString:@"Hello!"];
[myContainer setString:aString];
NSLog(@"%@", myContainer);
[aString setString:@"Bye!"];
NSLog(@"%@", myContainer);
aString = [myContainer string];
[aString setString:@"Bye, again!"];
NSLog(@"%@", myContainer);
It seems that aString
points to the string
member variable, which means when I change aString
I also change string
with it. I tried releasing aString
from the main()
method but then I get a compiler error. How do I fix this? Do I use the copy
method, or is there another way?
rcplusplus,
You asked:
It seems that aString points to the string member variable, which means when I change aString I also change string with it. I tried releasing aString from the main() method but then I get a compiler error. How do I fix this? Do I use the copy method, or is there another way?
The way to release any ARC item is to set it to nil
. This tells the compiler you are through with this item. It is released in the assignment.
Example:
[myContainer setString: nil];
myContainer.string = nil;
or, from within your class:
string = nil;
Andrew
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.