Search code examples
iosobjective-cmemory-managementnsarray

Is it right to assign the NSArray object to other NSArray object?


Just have confusion to improve the code quality in project. Is it right way to assign NSArray object to another NSArray object. But i haven't alloc the one NSArray object.

Is it right below code? Is there any issue for memory management issue?

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, weak) NSArray *array1;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *array2 = [[NSArray alloc] initWithObjects:@"A",@"B",@"C", nil];

    NSLog(@"array2 count : %lu",(unsigned long)array2.count);

    self.array1 = array2;

    NSLog(@"array1 count : %lu",(unsigned long)self.array1.count);


    // Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

Output :- 
2016-04-06 22:22:56.057 PhotoViewer[969:56203] array2 count : 3
2016-04-06 22:22:56.057 PhotoViewer[969:56203] array1 count : 3

My question, Is it required alloc for array1 object?

Ex : self.array1 = [[NSArray alloc] init];
     self.array1 = array2;

Solution

  • Your question addresses a core topic which is vital to understand when programming in any language - the difference between value and reference types and semantics.

    In summary: for an assignment between two variables of value type the actual bits used to represented the value are copied and after the assignment there is no connection between the two variables - altering one does not effect the other. As the bits are stored directly in the variable there is no need to allocate seperate storage for them. In Objective-C types such as double are value types.

    For reference types the bits used to represent the value are stored in storage distinct from the variable and the address of this distinct storage is what is stored in the variable. Assignment copies this address so after assignment the two variables refer to the same value. For mutable values altering the value via one variable effects what the other variable sees as well. Storage for reference types need to be managed separately from the variables, with new storage being allocated, and value bits being copied into it, when a new distinct value is required. Each distinct value is often called an object. For example, in Objective-C NSString is an immutable reference type, while NSMutableArray is a mutable one. In either case new distinct objects are created with alloc/init, new etc.. Simple assignment causes sharing.

    In your example the assignment is sharing an immutable array, there is no need to alloc a copy.

    There is much written on this, here are some slides from a university which explain it all quite clearly.

    HTH