I need to compare two array values one by one, if any value match with one another, i need to update the value and replace it from main array.
NSMutableArray is having an array of NSDictionary
NSArray is having an array of NSString objects.
My code is
NSMutableDictionary *dicOne = #{#"eveId":#"1",#"imgArray":#[#"one",#"two"]};
NSMutableDictionary *dicTwo = #{#"eveId":#"2",#"imgArray":#[#"Three",#"Four"]};
NSMutableArray *tempArray = [NSMutableArray array];
[tempArray addObject:dicOne];
[tempArray addObject:dicTwo];
NSArray *eventArray = [NSArray arrayWithObjects:#"1",#"2",#"3",nil];
NSString *fileName = #"Five";
for (int jj = 0; jj<[eventArray count]; jj++) {
NSString *topArrayEventId = [NSString stringWithFormat:#"%#",[eventArray objectAtIndex:jj]];
for (int kk = 0; kk<[tempArray count]; kk++) {
NSMutableDictionary *curentObj = [[tempArray objectAtIndex:kk]mutableCopy];
NSString *innerArrayEventId = [NSString stringWithFormat:#"%#",[curentObj valueForKey:#"eveId"]];
if ([innerArrayEventId isEqualToString:topArrayEventId]) {
NSLog(#"update inner array and replace main array");
NSMutableArray *imgArray = [NSMutableArray array];
imgArray = [[curentObj objectForKey:#"imgArray"]mutableCopy];
[imgArray addObject:fileName];
[curentObj setObject:[imgArray mutableCopy] forKey:#"imgArray"];
[tempArray replaceObjectAtIndex:kk withObject:[curentObj mutableCopy]];
}else{
NSLog(#"add new object to main array");
NSMutableDictionary* storeData = [NSMutableDictionary dictionary];
[storeData setObject:topArrayEventId forKey:#"eveId"];
NSMutableArray *imgArray = [NSMutableArray array];
[imgArray addObject:fileName];
[storeData setObject:imgArray forKey:#"imgArray"];
[tempArray addObject:storeData];
}
}
}
NSLog(#"final updation------->%#",tempArray);
I want output like below
(
{
eveId = 1;
imgArray = (
one,
two,
five
);
},
{
eveId = 2;
imgArray = (
Three,
Four,
five
);
}
{
eveId = 3;
imgArray = (
five
);
}
)
But i am not getting with that code..its giving wrong output. i having problem with inner loop.
Wrong output looks below
(
{
eveId = 1;
imgArray = (
one,
two,
Five
);
},
{
eveId = 2;
imgArray = (
Three,
Four,
Five
);
},
{
eveId = 1;
imgArray = (
Five,
Five
);
},
{
eveId = 2;
imgArray = (
Five,
Five
);
},
{
eveId = 2;
imgArray = (
Five,
Five
);
},
{
eveId = 3;
imgArray = (
Five,
Five
);
},
{
eveId = 3;
imgArray = (
Five,
Five
);
},
{
eveId = 3;
imgArray = (
Five,
Five
);
},
{
eveId = 3;
imgArray = (
Five,
Five
);
},
{
eveId = 3;
imgArray = (
Five,
Five
);
}
)
Predicate method using to achieve this
NSMutableDictionary *dicOne = #{#"eveId":#"1",#"imgArray":#[#"one",#"two"]};
NSMutableDictionary *dicTwo = #{#"eveId":#"2",#"imgArray":#[#"Three",#"Four"]};
NSMutableArray *tempArray = [NSMutableArray array];
[tempArray addObject:dicOne];
[tempArray addObject:dicTwo];
NSArray *eventArray = [NSArray arrayWithObjects:#"1",#"2",#"3",nil];
NSString *fileName = #"Five";
for (int jj = 0; jj<[eventArray count]; jj++) {
NSArray *resultArray = [tempArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"self.eveId = %#", [eventArray objectAtIndex:jj]]];
NSString *topArrayEventId = [NSString stringWithFormat:#"%#",[eventArray objectAtIndex:jj]];
if([resultArray count]>0) {
NSMutableDictionary *curentObj;
NSString *innerArrayEventId = [NSString stringWithFormat:#"%#",[[resultArray objectAtIndex:0] valueForKey:#"eveId"]];
if ([innerArrayEventId isEqualToString:topArrayEventId]) {
curentObj= [[resultArray objectAtIndex:0]mutableCopy];
NSMutableArray *imgArray = [NSMutableArray array];
imgArray = [[[resultArray objectAtIndex:0] objectForKey:#"imgArray"]mutableCopy];
[imgArray addObject:fileName];
[curentObj setObject:[imgArray mutableCopy] forKey:#"imgArray"];
[tempArray replaceObjectAtIndex:jj withObject:[curentObj mutableCopy]];
}
}
else {
NSMutableDictionary* storeData = [NSMutableDictionary dictionary];
[storeData setObject:topArrayEventId forKey:#"eveId"];
NSMutableArray *imgArray = [NSMutableArray array];
[imgArray addObject:fileName];
[storeData setObject:imgArray forKey:#"imgArray"];
[tempArray addObject:storeData];
}
}
NSLog(#"final updation------->%#",tempArray);
OutPut :
final updation------->(
{
eveId = 1;
imgArray = (
one,
two,
Five
);
},
{
eveId = 2;
imgArray = (
Three,
Four,
Five
);
},
{
eveId = 3;
imgArray = (
Five
);
}
)
Consider replacing NSMutableArray to use NSMutableSet
NSMutableArray *imgArray = [NSMutableArray array];
with
NSMutableSet *imgSet = [NSMutableSet set];
https://developer.apple.com/reference/foundation/nsmutableset
change this line
for (int kk = 0; kk<[tempArray count]; kk++)
with
for (int kk = jj; kk<[tempArray count]; kk++)
now run the code, is it working now?
Related
I know this may be a repeated question but I googled a lot but not able to find a suitable answer for me.
I have a NSMutableArray which has two NSDictionary with Keys and values which I need to populated on a UITableView. I have retrieved the value of the dictionary which I'm going populate using
NSMutableArray *mutArray = [responseArray valueForKey:#"Table"];
And I did like
NSMutableSet *names = [NSMutableSet set];
NSMutableArray *mutArray1 = [[NSMutableArray alloc] init];
for (id obj in mutArray) {
NSString *destinationName = [obj valueForKey:#"AssetClassName"];
if (![names containsObject:destinationName]) {
[mutArray1 addObject:destinationName];
[names addObject:destinationName];
}
}
Because the value AssetClassName is repeated. Now I have three values in mutArray1 which I need to show as UITableView section. Under AssetClassName I have Some data which determines the row in that section.
For retrieving that data I'm doing like
for (int i = 0; i < [mutArray1 count]; i++) {
NSMutableDictionary *a = [[NSMutableDictionary alloc] init];
NSMutableDictionary *b = [[NSMutableDictionary alloc] init];
for (NSDictionary *dict in mutArray) {
if ([[mutArray1 objectAtIndex:i] isEqualToString:[dict valueForKey:#"AssetClassName"]]) {
[a setObject:[dict objectForKey: #"SubAssetClassName"] forKey:#"Investment Categories"];
[a setObject:[dict valueForKey:#"Amount"] forKey:#"Amount (EUR)"];
[a setObject:[dict valueForKey:#"AllocationPercentage"] forKey:#"%"];
[a setObject:[dict valueForKey:#"ModelAllocationPercentage"] forKey:#"ModelAllocationPercentage"];
[b setObject:a forKey:[dict valueForKey:#"SubAssetClassName"]];
[mutdict setObject:b forKey:[dict valueForKey:#"AssetClassName"]];
}
}
}
mutdict is a NSMutableDictionary declared globally and is instantiate in viewdidLoad
mutdict = [[NSMutableDictionary alloc] init];
The values are inserted into mutdict as I needed. Each SubAssetClassName is added into AssetclassName accordingly.
But my problem is in my final dictionary i.e mutdict the values for SubAssetClassName is repeated.
Can anybody tell how to solve this.
My console
"AssetClassName" = {
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "HIGH YIELD BONDS";
"ModelAllocationPercentage" = 22;
};
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "HIGH YIELD BONDS";
"ModelAllocationPercentage" = 22;
};
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "HIGH YIELD BONDS";
"ModelAllocationPercentage" = 22;
};
};
"AssetClassName" = {
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "EMERGING MARKETS EQUITIES";
"ModelAllocationPercentage" = 10;
};
};
"AssetClassName" = {
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "STRUCTURED PRODUCTS";
"ModelAllocationPercentage" = 10;
};
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "STRUCTURED PRODUCTS";
"ModelAllocationPercentage" = 10;
};
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "STRUCTURED PRODUCTS";
"ModelAllocationPercentage" = 10;
};
};
}
Here I can see that all SubAssetClass values are same for each section but actually its not.
How can I solve this.
You need to create a new instance of your mutable dictionary inside the loop. Right now you create one instance and update it over and over. This results in one dictionary being added over and over.
Change you code as follows:
for (NSInteger i = 0; i < [mutArray1 count]; i++) {
NSMutableDictionary *b = [[NSMutableDictionary alloc] init];
for (NSDictionary *dict in mutArray) {
if ([[mutArray1 objectAtIndex:i] isEqualToString:[dict valueForKey:#"AssetClassName"]]) {
NSMutableDictionary *a = [[NSMutableDictionary alloc] init];
[a setObject:[dict objectForKey: #"SubAssetClassName"] forKey:#"Investment Categories"];
[a setObject:[dict valueForKey:#"Amount"] forKey:#"Amount (EUR)"];
[a setObject:[dict valueForKey:#"AllocationPercentage"] forKey:#"%"];
[a setObject:[dict valueForKey:#"ModelAllocationPercentage"] forKey:#"ModelAllocationPercentage"];
[b setObject:a forKey:[dict valueForKey:#"SubAssetClassName"]];
[mutdict setObject:b forKey:[dict valueForKey:#"AssetClassName"]];
}
}
}
Also, in most cases you should not be using valueForKey:. Use objectForKey: unless you have a clear and specific need to use key-value coding instead of simply getting an object from the dictionary for a given key.
I need to convert an NSMutableArray to an NSArray from JSON. I loaded the JSON and put it in an NSMutableArray.
NSMutableArray *banner = [[NSMutableArray alloc] init];
banner = [responseObject objectForKey:#"banner"];
This is test for loop:
for(int i = 0; i < [slider count]; i++) {
NSLog(#"%#", [[banner objectAtIndex:i] objectForKey:#"resim"]); }
This is log from the JSON:
(
{
id = 1;
resim = "http://localhost/sample_Files/banner_api/1.jpg";
},
{
id = 2;
resim = "http://localhost/sample_Files/banner_api/2.jpg";
},
{
id = 3;
resim = "http://localhost/sample_Files/banner_api/3.jpg";
}
)
I want to set all of this to be like the below NSArray:
NSArray *allImages = #[#"http://localhost/sample_Files/banner_api/1.jpg",#"http://localhost/sample_Files/banner_api/2.jpg",#"http://localhost/sample_Files/banner_api/3.jpg"];
How can I do this?
NSMutableArray * muArr = [NSMutableArray new];
for(NSDictionary * dict in yourMuArr) {
[muArr addObject:dict[#"resim"]];
}
NSArray * allImages = [NSArray arrayWithArray:muArr];
I've created NSDictionary of sorted arrays by name organized by first letter (see results below). When I use the command allKeys for that same Dictionary, the order is not the same. I need the order the same because this NSDictionary is used in UITableview and should be alphabetical.
- (NSDictionary*) dictionaryNames {
NSDictionary *dictionary;
NSMutableArray *objects = [[NSMutableArray alloc] init];
NSArray *letters = self.exhibitorFirstLetter;
NSArray *names = self.exhibitorName;
for (NSInteger i = 0; i < [self.exhibitorFirstLetter count]; i++)
{
[objects addObject:[[NSMutableArray alloc] init]];
}
dictionary = [[NSDictionary alloc] initWithObjects: objects forKeys:letters];
for (NSString *name in names) {
NSString *firstLetter = [name substringToIndex:1];
for (NSString *letter in letters) { //z, b
if ([firstLetter isEqualToString:letter]) {
NSMutableArray *currentObjects = [dictionary objectForKey:letter];
[currentObjects addObject:name];
}
}
}
NSLog(#"%#", dictionary);
NSLog(#"%#", [dictionary allKeys]);
return dictionary;
}
B = (
"Baker's Drilling",
"Brown Drilling"
);
C = (
"Casper Drilling"
);
J = (
"J's, LLC"
);
N = (
"Nelson Cleaning",
"North's Drilling"
);
T = (
"Tim's Trucks"
);
Z = (
"Zach's Main",
"Zeb's Service",
"Zen's"
);
}
J,
T,
B,
N,
Z,
C
)
NSDictionary is not an ordered collection. There's no way to control how it orders things, and it may change completely depending on OS version, device type, and dictionary contents.
I just put the NSDictionary in sorted array:
- (NSArray*)sortAllKeys:(NSArray*)passedArray{
NSArray* performSortOnKeys = [passedArray sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
return performSortOnKeys;
}
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
How do you split an array of objects into an array of array of objects?
say I want to split into groups of 4, how do I do that?
[a,b,c,d,e,f,g,h] =>
[a,b] [c,d] [e,f] [g,h]
or maybe if I specify that I want to split into groups of 3, then the result should be
[a,b,c], [d,e,f], [g,h]
it should also work if h doesn't exist.
Try this logic.....
NSArray *arr = [[NSArray alloc]initWithObjects:#"One",#"Two",#"Three",#"Four",#"Five",#"Six",#"Seven",nil];
NSMutableArray *arrNew = [[NSMutableArray alloc]init];
int numberofSubArrs = 3; // change this to check the logic
for (int i=0; i<numberofSubArrs; i++) {
NSMutableArray *arrrr = [[NSMutableArray alloc]init];
[arrNew addObject:arrrr];
}
int m = 0;
for (int k=0; k<[arr count]; k++) {
[[arrNew objectAtIndex:m]addObject:[arr objectAtIndex:k]];
m++;
if (m == numberofSubArrs) {
m=0;
}
}
int g=0;
int p=0;
while(p<[arr count]) {
for (int z=0; z<[[arrNew objectAtIndex:g] count]; z++) {
[[arrNew objectAtIndex:g] replaceObjectAtIndex:z withObject:[arr objectAtIndex:p++]];
}
g++;
}
NSLog(#"Required Array is:%#",[arrNew description]);
Try this as a starting point:
NSArray *array = [NSArray arrayWithObjects:#"a", #"b", #"c", #"d", #"e", #"f", #"g", #"h", nil];
NSMutableArray *manyArrays = [NSMutableArray array];
int numberOfElementsInSubArrays = 2;
int numberOfSubArrays = ceil((float)[array count] / (float)numberOfElementsInSubArrays);
for (int i = 0; i < numberOfSubArrays; i++) {
NSMutableArray *subArray = [NSMutableArray array];
for (int j = 0; j < numberOfElementsInSubArrays; j++) {
if (i*numberOfElementsInSubArrays+j < [array count]) {
NSLog(#"Array: %d Value:%#", i, [array objectAtIndex:i*numberOfElementsInSubArrays+j]);
[subArray addObject:[array objectAtIndex:i*numberOfElementsInSubArrays+j]];
}
}
[manyArrays addObject:subArray];
}
Give this a try.
NSMutableArray *splitted = [NSMutableArray array];
id firstItem, secondItem;
for (NSInteger i=0; i <= [originalArray count]-1; i+=2) {
#try {
firstItem = [originalArray objectAtIndex:i];
secondItem = [originalArray objectAtIndex:i+1];
}
#catch (NSException *exception) {
secondItem = [NSNull null];
}
#finally {
[splitted addObject:#[firstItem,secondItem]];
}
}