Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • When to use copy Attribute in declaring a property in objective c

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 435
    Comment on it

    We all use attributes in Objective C to declare properties. Attributes commonly used are strong, nonatomic, weak, assign. But we never take it seriously why we are using these attributes.


    One of the common mistakes I often see is the wrong use of retain/'strong' attribute in the declaration of NSString property.


    Let us understand it via a code snippet

    @interface Employee : NSObject
    @property (nonatomic, strong) NSString* name;
    @end
    

    Now according to the above code what you understood is it can never be changed without a setter but it can be changed without using a setter.


    Someone have the below code which can alter the data.


    NSMutableString *name = [NSMutableString stringWithString:@"Hello"];
    
    Employee *e = [Employee new];
    e.name = name;
    
    // Output is 'Hello'
    NSLog(@"e.name = %@", e.name);
    
    // e.name is changed by below code
    [name appendString:@" World"];
    
    // Output is 'Hello World'
    NSLog(@"e.name = %@", e.name);
    

    Lets say If we have property and its type has a mutable subclass, such as NSString, NSArray, NSDictionary, and if in our interface we require the property to be immutable, the use of copy attribute will prevent the above side-effect to be happened.


    Change the code snippet as below:

    @interface Employee : NSObject
    @property (nonatomic, copy) NSString* name;
    @end
    

    Run the application again and you will see the output as 'Hello' only. It can only be changed by a setter. This is an example for NSString. The same can be implemented for NSArray and NSDictionary.


    You can change the attribute of property in Employee interface to 'copy' or 'strong' and check the changes.


    Download the above code from the attachment.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: