I have an NSMutableArray populated with NSIntegers. I need to loop through the array. I could do:
// given NSMutableArray *array of NSIntegers
NSUInteger n = [array count];
for (NSInteger i = 0; i < n; i++) {
NSInteger x = [array objectAtIndex:i];
// query SQLite WHERE id = x
}
However, it seems that a for (object in array) loop would be cleaner. iOS 5 does not accept NSIntegers or NSNumbers as objects in for-in loops. Should I loop through the array with NSObjects, casting the NSObject to an NSInteger during each iteration? Is there another way? Or is a for loop like the one above the cleanest solution to this problem?
In Objective-C you can use a for-in loop with NSNumber like this:
NSArray *array = /*NSArray with NSNumber*/;
for (NSNumber *n in array) {
NSLog(#"i: %d", [n intValue]);
}
Check this out.
Mostly, you will not be allowed to have an NSMutableArray of NSUInteger (aka unsigned long) as it's not an objective-c object.
You may use the c style.
NSUInteger array[] = {value1,value2,value3};
int size = sizeof(array)/sizeof(array[0]);
for (int i=0; i<size; i++) {
NSInteger value = array[i];
// do whatever you want
}
Related
I'm trying to shuffle an NSMutableArray so that its order will be mixed up every-time someone loads the view.
In my -(void)viewDidLoad I'm putting the following code (as suggested by other users):
NSMutableArray *shuffleTwo = [self.chosenTeamDict objectForKey:#"clubs"];
int random = arc4random() % [shuffleTwo count];
for (int i = 0; i < [shuffleTwo count]; i++) {
[shuffleTwo exchangeObjectAtIndex:random withObjectAtIndex:i];
}
NSLog(#"%#", shuffleTwo);
But when I do this and try and run the page, I get the following error:
2012-07-09 18:42:16.126 Kit-Quiz[6505:907] (null)
libc++abi.dylib: terminate called throwing an exception
Can anyone advice either a new way of shuffling this array, or advice me on how to avoid this error..!? I'm building for iOS 5 and I'm using Xcode45-DP1. Thanks in advance!
(EDIT)
I've also tried this method and I get the same error:
NSMutableArray *shuffledArray = [[NSMutableArray alloc] init];
NSMutableArray *standardArray = [self.chosenTeamDict objectForKey:#"clubs"];
for(int s = 0; s < [standardArray count]; s++){
int random = arc4random() % s;
[shuffledArray addObject:[standardArray objectAtIndex:random]];
}
NSLog(#"%#", shuffledArray);
NSMutableArray *standardArray = [self.chosenTeamDict objectForKey:#"clubs"];
int length = 10; // int length = [yourArray count];
NSMutableArray *indexes = [[NSMutableArray alloc] initWithCapacity:length];
for (int i=0; i<10; i++) [indexes addObject:[shuffledArray objectAtIndex:i]];
NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:length];
while ([indexes count])
{
int index = rand()%[indexes count];
[shuffle addObject:[indexes objectAtIndex:index]];
[indexes removeObjectAtIndex:index];
}
for (int i=0; i<[shuffle count]; i++) NSLog(#"%#", [shuffle objectAtIndex:i]);
NSLog(#"%#", shuffle);
^^ ANSWER
Try Fisher-Yates shuffle. It goes like this:
int count = shuffledArray.count;
for(int i=count; i>0; i--) {
int j = arc4random_uniform(count);
[shuffledArray exchangeObjectAtIndex:j withObjectAtIndex:i];
}
make sure that your array is non-nil and all the entries are allocated objects :)
Source: Fisher-Yates Shuffle
First, you really should enable exception breakpoints. In XCode on the left-hand panel, click the breakpoint tab, click the "+" sign at the bottom-left -> exception breakpoint -> done.
I suspect your problem lies here:
int random = arc4random() % [shuffleTwo count];
If [shuffleTwo count] evaluates to zero (also if shuffleTwo is nil) it will throw a division by zero exception. Edit: Doesn't seem to be the case in Objective-C.
I want to initialize an NSArray with numbers starting from 0,1,2,3... I know the count of the array. For example:
I have an array that needs to be initialized with 5 (count) as capacity. Now I want to initialize this array with 0,1,2,3,4 and I need to initialize it dynamically.
If the count of the array is 10, I need to initialize the array with 0,1,2,3,4,5,6,7,8,9 at respective indexes. The problem is that count of the array changes dynamically and I need to initialize it accordingly.
Can someone suggest me any idea on how to implement this?
NSMutableArray* arrOfObject = [[NSMutableArray alloc] init];
for(int i=0; i< [arr count]; i++)
{
arrOfObject addObject:[NSNumber numberWithInt:i];
}
Initialize a mutable array. Then add the numbers in a loop. Optionally initialize a new non-mutable array with your mutable one using arrayWithArray:.
int count = 5;//suppose this you want
NSMutableArray *array = [NSMutableArray array];
for(int i=0 ; i< count; i++) {
[array addObject:[NSNumber numberWithInt:i];
}
You just need to pass the count from where you want it, and it will dynamically generate your desired array.
Use NSMutableArray then just add as many as you need
int count = 10;
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i=0;i<count;i++) {
[array addObject:[NSNumber numberWithInt:i]];
}
Here I am having a situation, I'm using the following code:
int x=0;
for (int i=0; i<=[arrayDeals count]-1; i++) {
x++;
//NSString *deal = [arrayDeals objectAtIndex:i];
combinedArr = [[NSMutableArray alloc]initWithObjects:
[CustomObject customObjectWithName:[arrayDeals objectAtIndex:i] andNumber:x],nil];
}
I need to load the values from arrayDeals and the 'x' value into combinedArr. So, I put this in a for loop. But i got only one value from each arrays. What is went wrong here? Please help me. (here CustomObject is a NSObject)
Thank you.
Well there are many things wrong with the code you posted, but I think this is what you want:
int x = 0;
NSMutableArray *combinedArr = [[NSMutableArray alloc] init]:
NSInteger count = [arrayDeals count];
for (int i = 0; i < count; i++) {
x++;
CustomObject *customObject = [CustomObject customObjectWithName:[arrayDeals objectAtIndex:i] andNumber:x];
[combinedArr addObject:customObject];
}
To give you some idea of what is wrong with the code you posted:
combinedArr = [[NSMutableArray alloc]initWithObjects:
[CustomObject customObjectWithName:[arrayDeals objectAtIndex:i] andNumber:x],nil];
Here you create a new NSMutableArray to which you assign an new object to taked the object from the array arrayDeals. But you create this NSMutableArray for every item in the array arrayDeals and you assign them to the same variable.
So each iteration you leak the NSMutableArray.
Also :
for (int i=0; i<=[arrayDeals count]-1; i++) {
is the same as
for (int i=0; i < [arrayDeals count]; i++) {
but the count is called every time you iterate, so as per my example I saved the count in a int to just speed things up.
You could even speed the code up using fast Enumeration:
NSInteger x = 0;
NSMutableArray *combinedArr = [[NSMutableArray alloc] init]:
for (id object in arrayDeals) {
id secondObject = [secondArray itemAtIndex:x];
// Arrays start at 0 so only up it after we've got the object.
x++;
CustomObject *customObject = [CustomObject customObjectWithName:object andNumber:x];
[combinedArr addObject:customObject];
}
I have NSInteger variable, for example NSInteger example=1256 and i need an array with elements of this variable.
so first element of array is array[0] = 1
array[1] = 2
array[2] = 5 etc..
what way can i solve it ?
Here's about how I'd do it:
NSUInteger number = 1234567890;
NSMutableArray * numbers = [NSMutableArray array];
while (number > 0) {
NSUInteger lastDigit = number % 10;
[numbers insertObject:[NSNumber numberWithUnsignedInteger:lastDigit] atIndex:0];
number = number / 10;
}
You need to use NSMutableArray to be able to change entries. NSMutableArray can only hold objects, not primitive types like NSInteger. Also, if you are using NSMutableArray, you can't access the elements the same way as with a C array.
[array insertObject:[NSNumber numberWithInteger:2] atIndex:1];
You can convert your integer to a char* then iterate through it casting each character back to an int and adding it to a C array or, as Steven says, an NSArray of NSNumbers.
I am new to iPhone development. I want a Nsmutable array to hold numbers from 1 to 100. How can I do it? How can I implement in a for loop? Is there any other way to hold numbers in array in iPhone?
You can only add NSObject subclasses in Cocoa containers. In your case, you will have to wrap your integers in NSNumber objects:
NSMutableArray *array = [NSMutableArray array];
for( int i = 0; i < 100; ++i )
{
[array addObject:[NSNumber numberWithInt:i]];
}
To extract the values:
int firstValue = [[array objectAtIndex:0] intValue];
Use an NSNumber object:
[NSNumber numberWithInt:1];
The short hand solution
NSMutableArray *array = [NSMutableArray array];
for( int i = 0; i < 100; ++i )
{
[array addObject:#(i)];
}
int intValue = 10;
NSNumber *numberObj = #(intValue);