Why does this property need to be "preserved"?

Given the following definition of a class with retaining properties:

@interface FeedEntry : NSObject<NSCoding>
{
    NSURL*  url;
    NSData* source;
}

@property (retain) NSURL*   url;
@property (retain) NSData*  source;
@end

@implementation FeedEntry

@synthesize url;
@synthesize source;

-(void)encodeWithCoder:(NSCoder*)coder
{
    [coder encodeObject:url     forKey:@"url"];
    [coder encodeObject:source  forKey:@"source"];
}

Why the url property in the initWithCoder method needs to be "saved":

-(id)initWithCoder:(NSCoder*)coder
{
    url = [[coder decodeObjectForKey:@"url"] retain];
    source  = [coder decodeObjectForKey:@"source"];

    NSLog(@"got url=%@\n", url);
    return self;
}

In particular, why does the synthesized "get url" method not save the object? (I assume that the source property will also need to be preserved).

+5
source share
1 answer

Quick response:

When you install:

url = [[coder decodeObjectForKey:@"url"] retain];

you are not using @property. You manually set the value of an instance variable url. Therefore, you must also manually specify a value retain.

To set a variable using synthesized properties, you must call:

[self setUrl:[coder decodeObjectForKey:@"url"]];

or

self.url = [coder decodeObjectForKey:@"url"];

retain.

:

Objective-C @property @synthesize getter setter:

@interface MyClass
{
    id someValue;
}
@property (retain) id someValue;
@end

@implementation MyClass
@synthesize someValue;
@end

:

@interface MyClass
{
    id someValue;
}
- (id)someValue;
- (void)setSomeValue:(id)newValue;
@end

@implementation MyClass
- (id)someValue { return someValue; }
- (void)setSomeValue:(id)newValue
{
    [newValue retain];
    [someValue release];
    someValue = newValue;
}
@end

"" - . - , .

+16

All Articles