I have a class with a NSArray property using ARC with nothing fancy…
#import <Foundation/Foundation.h>
@interface MyClass : NSObject
property(nonatomic, strong) (NSArray *) myArray;
@end
#import "MyClass.h"
@implementation MyClass
@synthesize myArray = _myArray;
@end
If an attempt is made to use a method inside of another class to try to set that array it does not set it if only the array is passed; however, it does set if the class is passed, I’m not sure why that is….
The code that attempts this both ways is below…
MyClass *myClass = [[MyClass alloc] init];
[self setArrayByPassingArray:myClass.myArray];
NSLog (@"%@", myClass.myArray)
//result is null
[self setArrayByPassingClass:myClass];
NSLog (@"%@", myClass.myArray)
//result is test, test2...
-(void)setArrayByPassingArray:(NSArray *)arrayToSet {
arrrayToSet = [[NSArray alloc] initWithObjects: @"test", @"test2", nil];
}
-(void)setArrayByPassingClass:(MyClass *)classWithArrayToSet {
classWithArrayToSet.myArray = = [[NSArray alloc] initWithObjects: @"test", @"test2", nil];
}
I tried some other methods with just strings and the strings are not changed, so I’m not sure why they are changed if class containing them is passed…
Your
setArrayByPassingArray:method in the first example assigns the newly createdNSArrayto its parameter, which is passed by value, and is promptly discarded upon exiting from the method. What happens here is that a copy of the reference tomyArrayis made (not a copy of the array, only a copy of a reference to that array) before callingsetArrayByPassingArray:. That copy is no longer attached to themyArraymember ofMyClass.Your second example is not passing a class – it’s passing an instance of the class, and then it correctly uses the dot notation to assign the
myArrayproperty in your instance. That’s why this second example works, and the first example does not.If you use
NSMutableArrayinstead ofNSArraythroughout your program, you can rewrite your first example to make it work: