In the code below, I am trying to add objects to array. No error, but is not adding objects either. Sorry for asking this pretty basic question. Need help
The NS Object Definition
//DataDefinition.h
#import
@interface DataDefinition : NSObject
@property (nonatomic, retain) NSString *dataHeader;
@property (nonatomic, retain) NSMutableArray *dataDetails;
@end
The DataDefinition Implementation
#import "DataDefinition.h"
@implementation DataDefinition
@synthesize dataHeader;
@synthesize dataDetails;
@end
The Display header section
//DataDisplay.h
#import
#import "DataDefinition.h"
@interface DataDisplay : UITableViewController
@property (strong, nonatomic) NSMutableArray *dataSet;
@property (strong, atomic) DataDefinition *individualData;
@end
The Display implementation section
//DataDisplay.m
#import "DataDisplay.h"
@interface DataDisplay ()
@end
@implementation DataDisplay
@synthesize dataSet;
@synthesize individualData;
- (void)viewDidLoad
{
[super viewDidLoad];
individualData.dataHeader = @"Header1";
individualData.dataDetails = [[NSMutableArray alloc] initWithObjects:@"Header1-Detail1", @"Header1-Detail2", @"Header1-Detail3", nil];
//This didnot add
[dataSet addObject:individualData];
NSLog(@"Count of objects is %d:",[dataSet count]);
//Nor did this
dataSet = [[NSMutableArray alloc] initWithObjects:individualData, nil];
NSLog(@"Count of objects is %d:",[dataSet count]);
self.title = @"DataDisplay";
}
The issue is that
individualDatais never actually set to an instantiated object (in other words, it is never initialized).These kinds of oversights are common due to Objective-C’s non-error policy regarding sending messages to nil; it’s perfectly legal and often useful principle. This means that your code will never complain until you try to pass it to some method which will crash if it sees nil. Unfortunately, you are using
initWithObjects, which simply sees nil as the end of the (empty) list. If you had instead tried to use[NSArray arrayWithObject:individualData]you may have seen an error which would hint to you that you had nil instead of an object.Note that setting properties on nil is particularly tricky, since it looks like you are simply dealing with a C-syle lvalue, when actually it translates to a message-send call at runtime:
You can take your pick of solutions. The “cheap” way is to simply initialize it right there. The “better” way (usually) is lazy-instantiation (i.e. in the getter). Since the object is marked as atomic, you likely need to let the compiler write the getter for you, and just initialize it in viewDidLoad (or awakeFromNib, initWithCoder, or similar):