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)];
Related
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.
Terminating program with the error index 1 beyond bounds. Actually I am trying to parse the columns from csv file. I found few questions on stackoverflow similar to this issue but none of the answer is helpful
NSMutableArray *lines = [sourceFileString componentsSeparatedByString:#"\n"].mutableCopy;
NSArray *keys = [lines.firstObject componentsSeparatedByString:#","];
NSMutableArray *result = [NSMutableArray array];
for (int i = 0; i<keys.count; i++) {
[result addObject:#{keys[i] : [NSMutableArray array]}];
}
[lines removeObjectAtIndex:0];
for (NSString *line in lines) {
// Get a list of all values
NSArray *columns = [line componentsSeparatedByString:#","];
// Insert the value into the array of the proper key
NSMutableArray *values = result[1][keys[1]];
[values addObject:columns[1]];
NSLog(#"values %#",values);
}
check that your array contains empty indexes, the reason is you are check ing with the help of [line componentsSeparatedByString:#","] if any index is empty it surely crash , so in here in before checking remove the empty index from array using following concept
for (int j=[lines count]-1; j>=0; j--)
if ([[lines objectAtIndex:j] length] == 0)
[lines removeObjectAtIndex:j];
I am new at iOS Dev. I want to save two different arrays (array1 & array2) in 2 dimensional array. I know how to save data directly in two dimensional array but can't by save two different arrays in one.
NSString* path = [[NSBundle mainBundle] pathForResource:#"Aasvogel" ofType:#"txt"];
NSString* content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
NSArray* foo = [content componentsSeparatedByString: #","];
NSMutableArray *array1 = #[], *array2 = #[];
for ( int i = 0; i < [foo count]; i++ )
{
NSString* day = foo[i];
if ( i % 2 == 0 ) { [array1 addObject:day];}
else { [array2 addObject:day];}
}
// and here i have populated two arrays (array1 and array2)
// Now i want to save these arraya in below two dimensional array (dataArray) atIndex:0 and at Index:1
NSMutableArray *dataArray = [[NSMutableArray alloc] initWithCapacity: 2];
[dataArray addObject:[NSMutableArray arrayWithObjects:#"e",
#"el",
#"ale",
#"vela",
#"gavel",nil] atIndex:0];
[dataArray addObject:[NSMutableArray arrayWithObjects:#"Represents 50 in Roman numeral",
#"Building Wing",
#"Pub Brew",
#"Thin Parchment or membranes",
#"chairperson's hammer",nil] atIndex:1];
I have recently implemented 2D array into my application. Please check below code which is available at 2DArray
int capacity;
#property (nonatomic, strong) NSMutableArray *outerArray;
#define kCRL2DArrayEmptyKey #"kCRL2DArrayEmptyKey"
- (id) initWithRows:(int)x columns:(int)y
{
if (self = [super init])
{
capacity = y;
self.outerArray = [NSMutableArray array];
for (int i = 0; i < x; i++) {
NSMutableArray *innerArray = [NSMutableArray array];
for (int j = 0; j < y; j++) {
[innerArray addObject:kCRL2DArrayEmptyKey];
}
[self.outerArray addObject:innerArray];
}
}
return self;
}
you can try this
NSArray * firstArray, *secondArray;
NSArray * mainArray= [[NSArray alloc]initWithObjects: firstArray, secondArray, nil];
I am not sure about 2-dimensional array in iOS but if I were you I would be saved the two arrays within a dictionary such as
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setvalue:yourArray forKey:#"FirstArray"];
[dict setvalue:yourSecondArray forKey:#"SecondArray"];
And Use it accordingly.
There’s no such thing as a two (or more) dimensional NSArray. If you genuinely need an n-dimensional array object in iOS or OS X, you can of course roll your own, or you could instead create an NSArray of NSArray instances (which are columns and which are rows is entirely up to you). In that case, you could e.g. add items by doing
[[outerArray objectAtIndex:0] addObject:#"Foo"];
[[outerArray objectAtIndex:1] addObject:#"Bar"];
That said, for the problem you are tackling, it looks to me as if an NSDictionary might be more appropriate, e.g. with keys #"e", #"el" and values #"Represents 50 in Roman numerals", #"Building Wing".
If your concern is that the keys of NSDictionary are not held in sorted order, you can always extract the keys as an array and sort them. Or, if the keys change regularly, you might want to use a more sophisticated approach (e.g. keeping a separate sorted array of keys and inserting them into the right place when adding to the NSDictionary).
Also, you know that in modern Objective-C you can write e.g.
#[ #"a", #"b", #"c" ]
or
#{ #"a": #1, #"b": 2 }
rather than the very verbose forms you're using above?
this is how u add anything in a 2d array i.e an Array of arrays in objective-c
NSMutableArray *array 1 = [[NSMutableArray alloc]init];
NSMutableArray *array 2;
for(int col = 0;col <5;col++){
array2 = [[NSMutableArray alloc]init];
for(int row = 0;row<5;row++){
[array2 addObject:myItems];
}
[array1 addObject:array2];
}
hope this helps
use for loop to generate 2d array from 2 different array,
follow this stracture
int i, j;
for(i = 0; i < nrows; i++)
{
for(j = 0; j < ncolumns; j++)
array[i][j] = 0;
}
}
May be it will help you
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);
}
I have this NSArray:
NSArray* temp=[[NSArray alloc]
initWithObjects:#"one",#"five",#"two",nil];
for(NSString* obj in temp){
NSLog(#"current item:%# Next item is:%#",obj, ***blank***);
}
What needs to replace blank? Do I need to know the upcoming object?
This only works if your objects are unique (i. e. there are no identical objects in the array):
id nxt = nil;
int nxtIdx = [temp indexOfObject:idx] + 1;
if (nxtIdx < temp.count) {
nxt = [temp objectAtIndex:nxtIdx];
}
NSLog(#"current item:%# Next item is:%#", obj, nxt);
But in my opinion, this is a hack. Why not use a normal for loop with the index of the object:
for (int i = 0; i < temp.count; i++) {
id obj = [temp objectAtIndex:i];
id next = (i + 1 < temp.count) ? [temp objectAtIndex:i + 1] : nil;
}
Or (recommended) enumerate it using a block
[temp enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
id next = nil;
if (idx + 1 < temp.count) {
next = [temp objectAtIndex:idx + 1];
}
}];
Try using an NSEnumerator.
Code:
NSEnumerator *enumerator = [temp objectEnumerator];
id obj;
while (obj = [enumerator nextObject]) {
if ([enumerator nextObject] == nil) {
NSLog(#"This is the last object: %#", obj);
break;
}
NSLog(#"current item:%# Next item is:%#", obj, [enumerator nextObject]);
}
You can't do this with fast enumeration without a few lines of extra code (deriving the index, adding to it, checking its still in bounds).
You could enumerate using a block and add one to the idx parameter, but a better design (where you wouldn't risk or have to check for out of bounds exceptions) would be to remember the previous object instead, which will be nil on your first iteration.
You can get the index of your current object and look at the next with something similar to:
NSArray* temp=[[NSArray alloc] initWithObjects:#"one",#"five",#"two",nil];
for(NSString* obj in temp){
if([temp count] < [temp indexOfObject:obj]+1)
{
NSLog(#"current item:%# Next item is:%#",obj, [temp objectAtIndex:[temp indexOfObject:obj] + 1]);
}
}
To me it can sometimes be easier to do a traditional for loop in this case to have access to your index variable.
Using fast enumeration, this is the only way:
NSInteger index = [temp indexOfObject:obj];
if (index != NSNotFound && index < temp.count)
NSObject nextObject = [temp objectAtIndex:(index + 1)];
Note the if, you'll want to make sure you get a valid index, and that adding one to it doesn't put you out of bounds.