Add an object in a specific position of a NSArray - iOS - ios

Please suggestion only for NSArray.
NSArray *addressAry = [[arr1 valueForKey:#"var_offline_address"] componentsSeparatedByString:#"$#$"];
for (int i = 0; i<=addressAry.count; i++) {
NSString *str = [addressAry objectAtIndex:i];
if (str containsString:#"NA") {
NSString *strChange;
strChange = #"Address Not Available";

[myMutableArray insertObject:myObject atIndex:42];
To add an object to the front of the array, use 0 as the index:
[myMutableArray insertObject:myObject atIndex:0];

Use NSMutableArray. It has a method called:
- (void)insertObject:(ObjectType)anObject atIndex:(NSUInteger)index
Like:
[yourMutableArray insertObject: theObject atIndex: theIndex];
As it describes:
If index is already occupied, the objects at index and beyond are shifted by adding 1 to their indices to make room.
For more info see the official doc.

Related

How to add values or add object into NSArray in Objective C using for loop?

Well this is my code:
NSDictionary *dicto;
NSString *ndccode;
NSString *string=#" ";
for (int i=0; i<array.count; i++) {
dicto=[array objectAtIndex:i];
ndccode=[dicto objectForKey:#"NDCCode"];
string=[string stringByAppendingString:ndccode];
string=[string stringByAppendingString:#"\n"];
NSLog(#"%#",string);
}
NSLog(#"%#",string);
In the above code, i have values in dicto nsdictionary which loops one by one value and assigns to ndccode which is string. Then I am adding to string so that I can append it to the next line.
output :
name1
name2
name3
.....
Instead of assigning to the string. I want to assign it to an array.Could you please tell me how to assign it to an array for this example,since it is in loop. I want to use the array for later purposes.
Thank you in advance.
NSDictionary *dicto;
NSString *ndccode;
NSMutableArray *outputArray=[NSMutableArray new];
for (int i=0; i<array.count; i++) {
dicto=[array objectAtIndex:i];
ndccode=[dicto objectForKey:#"NDCCode"];
[outputArray addObject:ndccode];
}
or even more succinctly
NSArray *outputArray = [array valueForKey:#"NDCCode"];

Delete all objects from NSMutableArray starting from index 3

I have NSMutableArray named dishArray. I have total 15 objects in this array.
I only want first three objects in array and delete the rest array.
Is there any way (other then looping) to delete?
I know using loop I can achieve it, but I am looking for alternate way. May be like deleteArray From: To:
NSMutableArray *array = ...;
if ([array count] > 3) {
[array removeObjectsInRange:NSMakeRange(3, [array count] - 3)];
}
Use the function removeObjectsInRange.
if ([yourArray count] > 3)
[yourArray removeObjectsInRange:NSMakeRange(3, [yourArray count] - 3)];
Try with following code:
if ([wholeArray count] > 3)
NSArray* finalArray = [wholeArray removeObjectsInRange(2, wholeArray.count-3)];
NSRange r;
r.location = 0; // start position
r.length = 3; // end position
[arr removeObjectsInRange:r];
[testArray removeObjectsInRange:NSMakeRange(3, testArray.count-1)];

Loading NSMutableArray objects into an IBCollection of Labels

My problem is that when I use fast enumeration to load objects from my array, like so:
for(SetOfObjects *set in _myArray){
NSLog (#"%#"[set anObject];
}
It will print out my specified object without a problem, however when it comes time to assign these objects to an NSArray of labels. The last object returns as 0.
Like so:
for(SetOfObjects *set in _myArray){
for(UILabel *label in _arrayOfLabels){
int i = [set intObject];
NSString *string = [NSString stringWithFormat:#"%i",i];
label.text = string;
}
}
I think, I have gone wrong here. The code works, but the problem is that all labels are then set as 0.
Any tips welcome.
You are iterating the labels within each SetOfObjects instance, when in fact you want to iterate both arrays at the same time, which cannot be done using fast enumeration.
Instead revert to indexed-access of both arrays:
NSInteger count = [_myArray count];
NSAssert([_arrayOfLabels count] == count, #"Different array sizes!");
for (NSInteger index = 0; index < count; index++) {
SetOfObjects *set = _myArray[index];
UILabel *label = _arrayOfLabels[index];
int i = [set intObject];
NSString *string = [NSString stringWithFormat:#"%i",i];
label.text = string;
}
Note the assertion to check that both arrays are the same size.
EDIT: Oops, i was a bad variable name to choose for the index...

Trying to create an array of dictionaries, keep getting the same dictionary repeated in the array

I'm trying to use NSData to pull information out of a text file, and then load it into a dictionary.
First I create a string of the text file, and load each record into an array.
Then I break apart the each record into individual data elements.
The problem I'm having is that when the dictionary is fully populated, I then use addObject to load it into the array, which it does do successfully. The problem is that when the next loop creates a new dictionary, the same dictionary gets loaded into the array, and I end up an array of all the same dictionaries, instead of multiple different dictionary objects.
I'm guessing there is some simple mistake I'm making that is causing this error. Any help would be appreciated.
NSString *clientListFile = [NSURL URLWithString: #"/textfile"];
NSData *clientListDataFile = [NSData dataWithContentsOfFile:clientListFile];
NSString *clientListString = [[NSString alloc]initWithBytes:[clientListDataFile bytes] length:[clientListDataFile length] encoding:NSUTF8StringEncoding];
NSString *returnDelimiter = #"\n";
NSString *commaDelimiter = #",";
NSString *exclamationDelimiter = #"!";
NSArray *keysAndObjects = [[NSArray alloc]init];
NSMutableDictionary *clientList = [[NSMutableDictionary alloc]init];
NSMutableArray *clientListOfDictionaries = [[NSMutableArray alloc]init];
NSArray *sentenceArray = [clientListString componentsSeparatedByString:returnDelimiter];
for (int i = 0; i < [sentenceArray count]; i=i+1) {
[clientList removeAllObjects]; //to start with a fresh dictionary for the next iteration
NSString *recordSentence = [sentenceArray objectAtIndex:i];
NSArray *attributes = [recordSentence componentsSeparatedByString:commaDelimiter];
for (int j = 0; j < [attributes count]; j = j+1) {
NSString *pairsOfItems = [attributes objectAtIndex:j];
//a small arry, of only two objects, the first is the key, the second is the object
keysAndObjects = [pairsOfItems componentsSeparatedByString:exclamationDelimiter];
[clientList setObject:[keysAndObjects lastObject] forKey:[keysAndObjects firstObject]];
}
[clientListOfDictionaries addObject:clientList];
}
When I used NSLog to see what's in the dictionary, I mulitple objects of the same dictionary repeated, even though up earlier in the iteration, I can see that the code is creating separate and unique dictionaries.
Instead of this line
[clientListOfDictionaries addObject:clientList];
you can have
[clientListOfDictionaries addObject:[[NSArray alloc] initWithArray:clientList];
That way you will be adding new arrays to clientListOfDictionaries instead of the same one.
Move this line:
NSMutableDictionary *clientList = [[NSMutableDictionary alloc]init];
to just after the first for loop line and then delete the line:
[clientList removeAllObjects];
It's important to create a new dictionary for each iteration.
You should also delete the following line:
NSArray *keysAndObjects = [[NSArray alloc]init];
and change:
keysAndObjects = [pairsOfItems componentsSeparatedByString:exclamationDelimiter];
to:
NSArray *keysAndObjects = [pairsOfItems componentsSeparatedByString:exclamationDelimiter];
You are allocated and initialising your clientList dictionary outside of the for loop, so you only have one dictionary, which you are storing in your array multiple times. Adding the dictionary to the array does not copy it, it merely adds a pointer to the object.
you need to move
NSMutableDictionary *clientList = [[NSMutableDictionary alloc]init];
inside your first for loop in place of
[clientList removeAllObjects];
Also, componentsSeparatedByString: returns an NSArray, so you don't need to allocate and initialise one. You can simply define the variable -
NSArray *keysAndObjects;
Because you're using the same clientList variable for each iteration of the loop. You need to create a whole new dictionary object each time.
Try this modified code:
NSData *clientListDataFile = [NSData dataWithContentsOfFile:clientListFile];
NSString *clientListString = [[NSString alloc]initWithBytes:[clientListDataFile bytes] length:[clientListDataFile length] encoding:NSUTF8StringEncoding];
NSString *returnDelimiter = #"\n";
NSString *commaDelimiter = #",";
NSString *exclamationDelimiter = #"!";
NSArray *keysAndObjects = nil;
NSMutableArray *clientListOfDictionaries = [[NSMutableArray alloc] init];
NSArray *sentenceArray = [clientListString componentsSeparatedByString:returnDelimiter];
for (NSUInteger i = 0; i < [sentenceArray count]; ++i) {
NSMutableDictionary *clientList = [[NSMutableDictionary alloc] init]; //to start with a fresh dictionary for the next iteration
NSString *recordSentence = [sentenceArray objectAtIndex:i];
NSArray *attributes = [recordSentence componentsSeparatedByString:commaDelimiter];
for (NSUInteger j = 0; j < [attributes count]; ++j) {
NSString *pairsOfItems = [attributes objectAtIndex:j];
//a small arry, of only two objects, the first is the key, the second is the object
keysAndObjects = [pairsOfItems componentsSeparatedByString:exclamationDelimiter];
[clientList setObject:[keysAndObjects lastObject] forKey:[keysAndObjects firstObject]];
}
[clientListOfDictionaries addObject:clientList];
}
An alternate option, though likely less efficient, is to to change the line:
[clientListOfDictionaries addObject:clientList];
to
[clientListOfDictionaries addObject:[clientList copy]];
That lets you keep using the same clientList variable, since you're adding a copy of it to the clientListOfDictionaries array. I just point that out because it might help you understand what's going on.
Also, note that I changed this line for you:
NSArray *keysAndObjects = [[NSArray alloc]init];
to
NSArray *keysAndObjects = nil;
Because it's just a pointer that is set by your call to componentsSeparatedByString, you don't need to allocate an array for it. That array will just vanish in your first iteration of the loop.
Should be added the new dictionary to array. Otherwise it will not add to an array. Every object in array have same dictionary mapping. So it will give you the same dictionary value. Create new dictionary for every object and add to array.
for (int i = 0; i < [sentenceArray count]; i=i+1) {
NSMutableDictionary *clientList = [[NSMutableDictionary alloc]init];
NSString *recordSentence = [sentenceArray objectAtIndex:i];
NSArray *attributes = [recordSentence componentsSeparatedByString:commaDelimiter];
for (int j = 0; j < [attributes count]; j = j+1) {
NSString *pairsOfItems = [attributes objectAtIndex:j];
//a small arry, of only two objects, the first is the key, the second is the object
NSArray *keysAndObjects = [pairsOfItems componentsSeparatedByString:exclamationDelimiter];
[clientList setObject:[keysAndObjects lastObject] forKey:[keysAndObjects firstObject]];
}
[clientListOfDictionaries addObject:clientList];
}

How can i read first item inside multiple arrays in IOS

I have this Array, and i need all first elements.
I can only read one with this
vc.ArrayListaFotos = [[listaImagens objectAtIndex:(indexPath.row * 3)] valueForKey:#"Caminho"];
But I can't read others first itens inside array 1,2,3...
Can someone help me please ?
You are using the wrong reference. You should do that:
NSMutableArray *arrayDeImagensParaOProdutoSelecionado = [NSMutableArray arrayWithObjects:nil];
for (NSArray *tempArray in listaImagens) {
if ([[NSString stringWithFormat:#"%#", [tempArray valueForKey:#"idProduto"]] isEqualToString:[NSString stringWithFormat:#"%#", [[produtos objectAtIndex:(indexPath.row * 3)] valueForKey:#"id"]]]) {
[arrayDeImagensParaOProdutoSelecionado addObject:tempArray];
}
}
Hope it help.
for(NSArray *innerArray in outerArray) {
NSObject *firstObject = [innerArray firstObject];
// do whatever you need to with firstObject
NSLog(#"%#",firstObject);
}

Resources