Reputation: 540
I want to add in an array 3 different arrays .. i really don't know how it works .. i've tried several ways but none did work. Can anyone help me please ?
#import "CoursesModel.h"
@implementation CoursesModel
@synthesize courses=_courses,coursesA=_coursesA,coursesB=_coursesB,coursesC=_coursesC;
-(NSArray *) coursesA
{
if(!_coursesA)
{
_coursesA = [[NSArray alloc]initWithObjects:@"A 1",A 2",A 3", nil];
}
return _coursesA;
}
-(NSArray *) coursesB
{
if(!_coursesB)
{
_coursesB = [[NSArray alloc]initWithObjects:@"B 1",@"B 2",@"B 3", nil];
}
return _coursesB;
}
-(NSArray *) coursesC
{
if(!_coursesC)
{
_coursesC = [[NSArray alloc]initWithObjects:@"C 1",@"C 2",@"C 3", nil];
}
return _coursesC;
}
-(NSMutableArray *) courses
{
if(!_courses)
{
_courses = [[NSMutableArray alloc]initWithCapacity:3];
[_courses addObject:_coursesA];
[_courses addObject:_coursesB];
[_courses addObject:_coursesC];
}
return _courses;
}
@end
This is the code i tried using but when i tried using the values from the array courses it did not work properly. For example, i want to call the first row from the array "coursesA" if i enter "self.courses[0][0]" it gives me this error
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
Thanks for helping
Upvotes: 0
Views: 79
Reputation: 31016
Use the property specifiers so that you invoke the appropriate getters for the arrays you're putting into courses
.
E.g.:
[_courses addObject:self.coursesA];
[_courses addObject:self.coursesB];
[_courses addObject:self.coursesC];
If I make these changes to your code, clean up the @"" typos, define the matching properties, and then simply call the following...
NSLog(@"From array %@", self.courses[0][0]);
...I get "2015-03-19 20:37:34.310 Test[12205:468173] From array A 1" printed in the console.
Upvotes: 2
Reputation: 16149
First, _coursesA(B & C) is nil when you called, and _courses wont insert nil
.
[_courses addObject:self.coursesA];
[_courses addObject:self.coursesB];
[_courses addObject:self.coursesC];
Then call it in any controller:
CoursesModel *c = [CoursesModel new];
NSArray *a = c.courses;
DLog(@"%@ %@",a,c.courses[0][0]);
But for your issue I guess your self.mc = nil
, check it.
Upvotes: 1