Question about the installer in objective-c

This is an example from the Objective-C 2.0 programming language. I'm just wondering, in the setter below, can I use value = [newValue retain] instead value = [newValue copy]?

    @interface MyClass : NSObject

{

    NSString *value;

}

@property(copy, readwrite) NSString *value;

@end



// assume using garbage collection

@implementation MyClass

@dynamic value;



- (NSString *)value {

    return value;

}



- (void)setValue:(NSString *)newValue {

    if (newValue != value) {

       value = [newValue copy];

    }

}

@end
+3
source share
4 answers

The fastest and safest way is to add @synthesize valueto the top of your implementation, and the compiler will automatically generate these methods.

, NSMutableString, . "" (, , , ), copy. ( , ?), , , - , , , , , .

NSMutable copy, , . (NSString ..) copy retain. .

value, . :

-(void)setValue:(NSString*)newvalue
{
    if (value != newvalue)
    {
        [value release];
        value = [newvalue copy];
    }
}

, setValue: , NSMutableString, retain, copy.

+7

, copy. - NSMutableString, .

0

It depends. If you use [newValue retain], another object may change the value of this pointer NSString. Usually you do not like this behavior.

0
source

setter method:

  -(void)setValue:(NSString*)newvalue{
        if (_value != newvalue)
        {
            [_value release];
            _value = nil;
            _value = [newvalue copy];

        }
   }
0
source

Source: https://habr.com/ru/post/1712782/


All Articles