I would like to create an array for iOS platform like the PHP syntax below, many thanks ~~
$createArray = array ();
for ($i = 0; $i<10; $i++) {
$createArray[$i]['name'] = $name;
$createArray[$i]['age'] = $age;
}
Save your values in NSDictionary and add that dictionary into your array
NSMutableArray *theArray = [NSMutableArray array];
for (int indexValue = 0; indexValue<10; indexValue++) {
NSMutableDictionary *theDictionary = [[NSMutableDictionary alloc] init];
[theDictionary setObject:name forKey:#"name"];
[theDictionary setObject:age forKey:#"age"];
[theArray addObject:theDictionary]
}
While Retrieving time,
NSString *name = [[theArray objectAtIndex:indexValue] objectForKey:#"name"];
NSString *age = [[theArray objectAtIndex:indexValue] objectForKey:#"age"];
you might find it helpful:
array = [[NSMutableArray alloc] init];
for (int i = 0; i < 8; i++) {
NSMutableArray *subArray = [[NSMutableArray alloc] init];
for (int j = 0; j < 8; j++) {
[subArray addObject:[NSNumber numberWithInt:0]];
}
[array addObject:subArray];
[subArray release];
}
also check this question
Try this.
array = [[NSMutableArray alloc] init];
for (int i = 0; i < 10; i++) {
NSMutableArray *subArray = [[NSMutableArray alloc] init];
for (int j = 0; j < 2; j++) {
//Do your Stuff
// [subArray addObject:name];
// [subArray addObject:Age];
}
[array addObject:subArray];
}
OR
Why can't try with the NSDictionary
You can use this. But this is not better way in IOS.
NSMutableArray *array[20];
for (int i=0;i< 20; i++)
{
array[i] = [NSMutableArray array];
for (int j=0;j<3;j++)
{
NSMutableDictionary *theDictionary = [[NSMutableDictionary alloc] init];
[theDictionary setObject:name forKey:#"name"];
[theDictionary setObject:age forKey:#"age"];
[[array[i] addObject:theDictionary]
}
}
First you to have set An NSMutableDictionary on .h file
#interface MSRCommonLogic : NSObject
{
NSMutableDictionary *twoDimensionArray;
}
then have to use following functions in .m file
- (void)setValuesToArray :(int)rows cols:(int) col value:(id)value
{
if(!twoDimensionArray)
{
twoDimensionArray =[[NSMutableDictionary alloc]init];
}
NSString *strKey=[NSString stringWithFormat:#"%dVs%d",rows,col];
[twoDimensionArray setObject:value forKey:strKey];
}
- (id)getValueFromArray :(int)rows cols:(int) col
{
NSString *strKey=[NSString stringWithFormat:#"%dVs%d",rows,col];
return [twoDimensionArray valueForKey:strKey];
}
Related
Below is my Code, When I Add Dictionary into NSMutableArray that time it works well but when I Put NSLog It will throw an Exception. So, Please Help me
//-->
arrMain = [[NSMutableArray alloc] init];
NSMutableArray *arrMainMenu = [[NSMutableArray alloc] init];
NSMutableArray *arrMainMenu2 = [[NSMutableArray alloc] init];
for(int i = 0; i < arrParent.count; i++)
{
NSMutableDictionary *dictMain = [arrParent objectAtIndex:i];
if([[dictMain valueForKey:E_UNDER] isEqualToString:#""])
{
NSString *titleMain = [dictMain valueForKey:E_PARAMETER_VALUE_NAME];
NSMutableArray *arrSubMenu = [[NSMutableArray alloc] init];
for (int j = 0; j <arrSub.count; j++)
{
NSMutableDictionary *dictSub = [[arrSub objectAtIndex:j] mutableCopy];
if([titleMain isEqualToString:[dictSub valueForKey:E_UNDER]])
[arrSubMenu addObject:dictSub];
}
if([arrSubMenu count])
{
[dictMain setValue:#"1" forKey:IS_EXAPANDABLE];
[dictMain setValue:#"0" forKey:IS_EXPANDED];
[arrSubMenu insertObject:dictMain atIndex:0]; //Here Add Key-Value Dictionary in Array
[dictMain setValue:arrSubMenu forKey:LIST_ID];
arrSubMenu = [[NSMutableArray alloc] init];
}
else
[dictMain setValue:#"0" forKey:IS_EXAPANDABLE];
[arrMainMenu addObject:dictMain];
}
}
NSLog(#"%#", arrMainMenu); //Here Throw Bad Access exception
[obj_DataModel setFilterMenu:arrMainMenu];
//-->
I need to sort array (in IOS) like this...
let us suppose that i have an NSMutableArray with : 1,2,3,4,5
i need to build a new array with the last object in the middle and the middle will replace the last : 1.2.5.4.3...
please help:
this is what i doing for now, i got only the 1.2.5 but i not success to put the 4.3 ...
NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:#1,#2,#3,#4,#5, nil];
int arrCount = (int)arr.count/2;
NSMutableArray *arr2 = [[NSMutableArray alloc] init];
for (int i = 0;i < arr.count; i++) {
if (i < arrCount) {
[arr2 addObject:arr[i]];
}
else{
index = i;
[arr2 addObject:arr.lastObject];
}
}
NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:#1,#2,#3,#4,#5, nil];
NSMutableArray *arr2 = [[NSMutableArray alloc] initWithArray:arr];
int middleIndex = (int)arr.count/2;
id middleObject = arr2[middleIndex];
[arr2 replaceObjectAtIndex:middleIndex withObject:arr2.lastObject];
[arr2 replaceObjectAtIndex:arr2.count-1 withObject:middleObject];
NSLog(#"%#", arr2);
Hi I would like to know how to do when you click a button it will add a new object in the array and it will not affect the other objects like this:
here is my code:
x = x + 1;
dictData = [[NSMutableDictionary alloc] init];
for (int i = 0; i < x; i++) {
[dictData setObject:[menuData itemName] forKey:#"dishName"];
[dictData setObject:#"1" forKey:#"quantity"];
[dictData setObject:[menuData itemPrice] forKey:#"price"];
[arrMut addObject:dictData];
}
This is the current output
{
name = charles1;
},{
name = charles1;
}
This is the expected output
{
name = charles1;
},{
name = charles2;
}
because you are adding a same dictionary
change it to
for (int i = 0; i < x; i++) {
dictData = [[NSMutableDictionary alloc] init]; // move this line to inside of the loop
[dictData setObject:[menuData itemName] forKey:#"dishName"];
[dictData setObject:#"1" forKey:#"quantity"];
[dictData setObject:[menuData itemPrice] forKey:#"price"];
[arrMut addObject:dictData];
}
or
for (int i = 0; i < x; i++) {
[arrMut addObject:[#{#"dishName" : [menuData itemName],
#"quantity" : #"1",
#"price" : [menuData itemPrice],
} mutableCopy]];
}
The [menuData itemName] method seems to be returning the same object everytime.
You could insert menuData objects in an array and then access a menuData object on each iteration of the for loop.
NSMutableArray *arrMenuData = //This array should contain the menuData objects
for (int i = 0; i < x; i++) {
dictData = [[NSMutableDictionary alloc] init]; // move this line to inside of the loop
[dictData setObject:[[arrMenuData objectAtIndex:i] itemName] forKey:#"dishName"]; //A typecast to menuData type may be required, please test.
[dictData setObject:#"1" forKey:#"quantity"];
[dictData setObject:[[arrMenuData objectAtIndex:i] itemPrice] forKey:#"price"];
[arrMut addObject:dictData];
}
I have a UITableView with custom cellView populated with an array (cf. functs) without section. My goal is to create a search bar (which is ok) with a list index (which is the problem).
After reading a lot of documentations, I plan to use these three methods: "numberOfSectionsInTableView", "sectionIndexTitlesForTableView" and "sectionForSectionIndexTitle"
How to create the NSDictionnary of functs array with the following structure?
//in viewDidLoad
// Initialize the functs array
Funct *funct1 = [Funct new];
funct1.name = #"AAA";
funct1.detail = #"detail1...";
funct1.image = #"a.jpg";
Funct *funct2 = [Funct new];
funct2.name = #"BBB";
funct2.prepTime = #"detail2...";
funct2.image = #"b.jpg";
functs = [NSArray arrayWithObjects:funct, funct2, nil]; //etc.
//For Index list: one section per letter
NSString *letters = #"a b c d e f g h i j k l m n o p q r s t u v w x y z";
self.indexTitlesArray = [letters componentsSeparatedByString:#" "];
Thanks in advance
Here you have a good tutorial with example project. It´s what you are looking for.
It´s an example for TableView indexed, but it has a good example for sections and rows
There is in this example this method very useful for you
static NSString *letters = #"abcdefghijklmnopqrstuvwxyz";
// This method returns an array of dictionaries where each key is a letter
// and each value is a group of words corresponding to the letter.
+ (NSArray *) wordsFromLetters {
NSMutableArray *content = [NSMutableArray new];
for (int i = 0; i < [letters length]; i++ ) {
NSMutableDictionary *row = [[[NSMutableDictionary alloc] init] autorelease];
char currentWord[WORD_LENGTH + 1];
NSMutableArray *words = [[[NSMutableArray alloc] init] autorelease];
for (int j = 0; j < WORD_LENGTH; j++ ) {
if (j == 0) {
currentWord[j] = toupper([letters characterAtIndex:i]);
}
else {
currentWord[j] = [letters characterAtIndex:i];
}
currentWord[j+1] = '\0';
[words addObject:[NSString stringWithCString:currentWord encoding:NSASCIIStringEncoding]];
}
char currentLetter[2] = { toupper([letters characterAtIndex:i]), '\0'};
[row setValue:[NSString stringWithCString:currentLetter encoding:NSASCIIStringEncoding]
forKey:#"headerTitle"];
[row setValue:words forKey:#"rowValues"];
[content addObject:row];
}
return content;
}
You can take the main idea from this resource, but if you prefer, I adapted the code. I think works fine
NSMutableArray *funcsArray = [NSMutableArray array];//Here you add all your functs objects
[funcsArray addObjects: funct1, funct2...];
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:#"name"
ascending:YES selector:#selector(localizedCaseInsensitiveCompare:)] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [funcsArray sortedArrayUsingDescriptors:sortDescriptors];
NSMutableArray *funcsArrayOrdered = [NSMutableArray array];//Here you add all your functs objects
NSMutableArray *funcsIndexed = [NSMutableArray array];
NSMutableArray *letters = [NSMutableArray array];
NSString *currentLetter = nil;
int numItems = [funcsArrayOrdered count];
for (Funct *functObj in funcsArrayOrdered) {
NSLog(#"funct: %#", functObj.name);
numItems--;
NSString *string = userT.name;
if (string.length > 0) {
NSString *letter = [[string substringToIndex:1] uppercaseString];
if ([currentLetter length] == 0) {
currentLetter = letter;
}
if (![letter isEqualToString:currentLetter] || numItems == 0) {
if ([letter isEqualToString:currentLetter] && numItems == 0) {
[letters addObject:functObj];
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setValue:currentLetter forKey:#"headerTitle"];
[dic setValue:letters forKey:#"rowValues"];
[funcsIndexed addObject:dic];
letters = [NSMutableArray array];
}else{
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setValue:currentLetter forKey:#"headerTitle"];
[dic setValue:letters forKey:#"rowValues"];
[funcsIndexed addObject:dic];
letters = [NSMutableArray array];
[letters addObject:functObj];
currentLetter = letter;
if (numItems == 0 && [funcsArrayOrdered count] > 1) {
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setValue:currentLetter forKey:#"headerTitle"];
[dic setValue:letters forKey:#"rowValues"];
[funcsIndexed addObject:dic];
}
}
}else {
[letters addObject:functObj];
}
}
}
Now you will have your array of Dictionaries ordered in funcsIndexed
I have an NSArray some thing like in the following format.
The group array is :
(
"Q-1-A1",
"Q-1-A9",
"Q-2-A1",
"Q-2-A5",
"Q-3-A1",
"Q-3-A8",
"Q-4-A1",
"Q-4-A4",
"Q-10-A2",
"Q-8-A2",
"Q-9-A2",
"Q-7-A1",
"Q-5-A2"
)
Now what i have to do is group the array elements some thing like this.
1 = ( "Q-1-A1","Q-1-A9")
2 = ("Q-2-A1","Q-2-A5",) ...
10 =("Q-10-A2")
can any one please help me how can i achieve this.
Thanks in advance.
Try
NSArray *array = #[#"Q-1-A1",
#"Q-1-A9",
#"Q-2-A1",
#"Q-2-A5",
#"Q-3-A1",
#"Q-3-A8",
#"Q-4-A1",
#"Q-4-A4",
#"Q-10-A2",
#"Q-8-A2",
#"Q-9-A2",
#"Q-7-A1",
#"Q-5-A2"];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
for (NSString *string in array) {
NSArray *components = [string componentsSeparatedByString:#"-"];
NSString *key = components[1];
NSMutableArray *tempArray = dictionary[key];
if (!tempArray) {
tempArray = [NSMutableArray array];
}
[tempArray addObject:string];
dictionary[key] = tempArray;
}
Create an NSMutableDictionary, then iterate through your 'group array'.
For each NSString object:
get the NSArray of componentsSeparatedByString:#"-"
use the second component to create a key and retrieve the object for that key from your mutable dictionary. If its nil then set it to an empty NSMutableArray.
add the original NSString to the mutable array.
Try this
NSArray *arrData =[[NSArray alloc]initWithObjects:#"Q-1-A1",#"Q-1-A9",#"Q-2-A1",#"Q-2-A5",#"Q-3-A1",#"Q-3-A8",#"Q-4-A1",#"Q-4-A4",#"Q-10-A2",#"Q-8-A2",#"Q-9-A2",#"Q-7-A1",#"Q-5-A2", nil ];
NSMutableDictionary *dictList = [[NSMutableDictionary alloc]init];
for (int i=0; i<[arrData count];i++) {
NSArray *arrItem = [[arrData objectAtIndex:i] componentsSeparatedByString:#"-"];
NSMutableArray *arrSplitedItems = [dictList valueForKey:[arrItem objectAtIndex:1]];
if (!arrSplitedItems) {
arrSplitedItems = [NSMutableArray array];
}
[arrSplitedItems addObject:[arrData objectAtIndex:i]];
[dictList setValue:arrSplitedItems forKey:[arrItem objectAtIndex:1]];
}
NSArray *sortedKeys =[dictList allKeys];
NSArray *sortedArray = [sortedKeys sortedArrayUsingComparator:^(id str1, id str2) {
return [((NSString *)str1) compare:((NSString *)str2) options:NSNumericSearch];
}];
for (int i=0; i<[sortedArray count]; i++) {
NSLog(#"%#",[dictList objectForKey:[sortedArray objectAtIndex:i]]);
}
listOfYourMainArray/// Its YOur main Array;
temArray = (NSArray *)listOfYourMainArray; // Add Your main array to `temArray`.
NSMutableDictionary *lastDic = [[NSMutableDictionary alloc] init]; /// YOu need to creat Dictionary for arrange your values.
for (int i = 0; i< listOfYourMainArray.count; i++)
{
for (int j = 0 ; j < temArray.count; j ++)
{
if (([[temArray objectAtIndex:j] rangeOfString:[NSString stringWithFormat:#"Q-%d", i] options:NSCaseInsensitiveSearch].location != NSNotFound))
{
[lastDic setValue:[temArray objectAtIndex:j] forKey:[NSString stringWithFormat:#"%d", i]];
}
}
}
NSLog(#"%#", lastDic)