I am new to iOS and want to create an NSArray
like this which contains an NSDictionary
.
[
{
Image: 1, 2,3
Title: 1,2,3
Subtitle:1,2,3
}
]
I have tried this.
NSArray *obj-image=@[@"Test.png",@"Test.png",@"Test.png"];
NSArray *obj-title=@[@"Test",@"Test",@"Test"];
NSArray *obj-subtitle=@[@"Test",@"Test",@"Test"];
NSDictionary * obj_dictionary ={ image : obj_image, title:obj_title, subtitle:obj_subtitle}
NSArray * obj_array= [obj_dictionarry];
But not working and how to access them.
First of all, you initialization of Arrays and Dictionaries is wrong. You cannot use "-" in the names, period.
Second, you need to allocate and then initialize the objects. This is how you do that with arrays:
NSArray *images = [NSArray arrayWithObjects: @"TestImage",@"TestImage",@"TestImage",nil];
NSArray *titles = [NSArray arrayWithObjects: @"TestTitle",@"TestTitle",@"TestTitle",nil];
NSArray *subtitles = [NSArray arrayWithObjects: @"TestSubTitle",@"TestSubTitle",@"TestSubTitle",nil];
Then you need Mutable dictionary and mutable arrays to work with the data (mutable means you can change the values inside, add or remove objects etc.)
This is the most basic example of what you are trying to achieve:
NSArray *images = [NSArray arrayWithObjects: @"TestImage",@"TestImage",@"TestImage",nil];
NSArray *titles = [NSArray arrayWithObjects: @"TestTitle",@"TestTitle",@"TestTitle",nil];
NSArray *subtitles = [NSArray arrayWithObjects: @"TestSubTitle",@"TestSubTitle",@"TestSubTitle",nil];
NSMutableArray *objectsMutable = [[NSMutableArray alloc] init];
for (NSString *string in images) {
NSMutableDictionary *dictMutable = [[NSMutableDictionary alloc] init];
[dictMutable setObject:string forKey:@"image"];
//determining the index of the image
NSInteger stringIndex = [images indexOfObject:string];
[dictMutable setObject:[titles objectAtIndex:stringIndex] forKey:@"title"];
[dictMutable setObject:[subtitles objectAtIndex:stringIndex] forKey:@"subtitle"];
NSDictionary *dict = [[NSDictionary alloc] init];
dict = dictMutable;
[objectsMutable addObject:dict];
}
NSArray *objects = objectsMutable;
NSLog(@"%@", objects);
Hope this helps.
As you can see, I'm going through the images array, capturing the index of each one, an then just apply values of other arrays from the same index into a mutable dictionary.
All I do after that is just make a regular dictionary and array to put the data inside. This is ho the Log will look:
(
{
image = TestImage;
subtitle = TestSubTitle;
title = TestTitle;
},
{
image = TestImage;
subtitle = TestSubTitle;
title = TestTitle;
},
{
image = TestImage;
subtitle = TestSubTitle;
title = TestTitle;
}
)
You have an array with three objects inside, each with their own image, title and subtitle.