I'm confused a bit about how @property works. My example is this... I have a XYZPerson class, in it I use @property for NSStrings of first and last names, and then an NSMutableArray to hold them. In main, I create an instance of the person (see code below), use the setters for the names... and then use NSLog to test if they print out... and they do. I then use the addObject function to add the names to the array, try to print them out using NSLog, but it returns NULL, because the array doesn't exist. If I then overwrite the init method to instantiate the array, now the array prints as expected. So why would @property create NSStrings without having to instantiate them elsewhere, while it won't do the same for an array, and possibly other things like sets and dictionaries?
//XYZPerson interface
@interface XYZPerson : NSObject
@property (strong, nonatomic) NSString *firstName;
@property (strong, nonatomic) NSString *lastName;
@property NSMutableArray *arr1;
@end
//XYZPerson implementation
#import "XYZPerson.h"
@implementation XYZPerson
@end
//main
#import <Cocoa/Cocoa.h>
#import "XYZPerson.h"
int main(int argc, const char * argv[])
{
XYZPerson *fredJones = [XYZPerson new];
fredJones.firstName = @"Fred";
fredJones.lastName = @"Jones";
[fredJones.arr1 addObject:@"Fred"];
[fredJones.arr1 addObject:@"Jones"];
NSLog(@"first name: %@", fredJones.firstName);
NSLog(@"last name: %@", fredJones.lastName);
NSLog (@"array contents: %@", fredJones.arr1);
return NSApplicationMain(argc, argv);
}
the strings exist, will print out, the array does not. ???
however, if I add this to the XYZ implementation... now the array works:
-(id) init
{
self = [super init];
if(self)
{
_arr1 = [[NSMutableArray alloc] init];
}
return self;
}