Auto increasing numbers in array - objective-c

i'm just starting out with Xcode and need some help. I have this array set up:
myArray = [NSMutableArray arrayWithObjects: item1type1, item1type, item1type3, item1type4, item1type5, item1type6, item1type7, item1type8, item1type9, nil];
Is it possible to auto-assign numbers to elements in a sequence? The logic is simple: item1type(i), item1type(i+1), item1type(i+2),...
Many thanks

There are too many magic numbers in this code, but here you go:
// Build an Array of keys #[#"item_1_type_1", #"item_1_type_2", ..., #"item_1_type_9"] programmatically
const int numberOfElements = 9;
NSMutableArray *keys = [NSMutableArray arrayWithCapacity:numberOfElements];
for (int i = 1; i <= numberOfElements; i++) {
[keys addObject:[NSString stringWithFormat:#"item_1_type_%d", i]];
}
// Extract chosen keys from JSON Dictionary into an Array, matching the
// order of the keys above.
NSDictionary *subDict = myJSONData[#"item1"];
NSArray *myArray = [subDict objectsForKeys:keys notFoundMarker:[NSNull null]];

Related

how to get the index on numbers generated by int arc4random()

How do you get the index of the number appearing from the arc4rand method?. If 4,1,2,3 appear how do you index them . Example 4 would be 0 in the array.
int rand=((arc4random()%4)+1);
For getting random number, i did like this:
Suppose, i have a mutable array
NSMutableArray * myArray = [[NSMutableArray alloc] init];
and i kept 5 data in this myArray.
Now I have to generate random number index from myArray.
int randomIndex = (arc4random() % ([myArray count]));
Here randomIndex is random index of array
try this one. you need to put all that values into array.
NSMutableArray * array = [[NSMutableArray alloc] initWithCapacity:4];
[array insertObject:#"4" atIndex:0];
[array insertObject:#"1" atIndex:1];
[array insertObject:#"2" atIndex:2];
[array insertObject:#"3" atIndex:3];
using array to get index in ios to add all values in array like this
//convert int to nsstring and add array
NSArray *array=[NSArray arrayWithObjects:NSStringFromInt(4),NSStringFromInt(1),NSStringFromInt(2),NSStringFromInt(3), nil];
//reverse process to get int value
int value=[[array objectAtIndex:index]integerValue];
I'm just guessing, you might look for this...
NSMutableArray *_array = [NSMutableArray array];
for (int i = 0; i < 10; i++) {
[_array addObject:#((arc4random()%4)+1)];
}

Objective C - Array With Numbers

Is there a nicer way to fill an array with numbers than what I use?
It's crazy how much I got to write just to fill an array with numbers so they can be used for a calculation in a loop. This is easier in other C based languages like PHP, As3, or Java.
NSArray *myArray = [NSArray arrayWithObjects:
[NSNumber numberWithInt:1000],[NSNumber numberWithInt:237], [NSNumber numberWithInt:2673], nil];
int total = 0;
for(int i = 0; i < [myArray count]; i += 1 ){
total += [[myArray objectAtIndex: i]intValue];
NSLog(#"%i", total);
}
Hopefully there is a shorter way... I just want to fill an array with ints... cant be that hard
I guess you have to use NSNumber for an NSArray. If you want to use ints I guess you'd have to use a c array:
NSInteger myArray[20];
for (int i=0;i<20;i++) {
int num=myArray[i];
//do something
}
NSNumber though is I guess the better approach for this language.
At least you can do fast enumeration to shorten code a bit:
for (NSNumber *n in myArray) {
int num = [n intValue];
//do something....
}
EDIT:
The question has been asked 3 years ago. There have been new literals established to make it easier to create objects like NSNumbers or NSArrays:
NSNumber *n = #100;
or
NSArray *array = #[#100,#50,#10];
Nice short alternative for looping specific integers:
NSArray *numbers = [#"1000,237,2673" componentsSeparatedByString:#","];
for (NSString *i in numbers) {
[i intValue]; // Do something.
}
First start with a C array:
NSInteger myCArray = { 1000, 237, 2673 };
// calculate number of elements
NSUInteger myCArrayLength = sizeof(myCArray) / sizeof(NSInteger;
Second, if you need an NSArray loop through this array and create one:
NSMutableArray *myNSArray = [NSMutableArray arrayWithCapacity:myCArrayLength];
for(NSUInteger ix = 0; ix < myCArrayLength; ix++)
[myNSArray addObject:[NSNumber numberWithInteger:myCArray[ix]];
You can wrap the second piece of code up as a category on NSArray if you're doing it a lot.
too late. but u can do the following too.
int total = 0;
nsarray *myArray = #[#1.8,#100,#299.8];
for(nsnumber *num in myArray){
total+=num;
}

Populating array with integers

Let's say I want to populate NSarray with 50 integers. We know that NSarray accept only objects. So I have to do 50 times
NSNumber *num1 = [NSNumber numberWithInit:10];
NSNumber *num2 = [NSNumber numberWithInit:212];
......
NSNumber *num50 = [NSNumber numberWithInit:12];
Is there more elegant way to achieve that, beacause looks stupid 50 lines of code only for create number objects ?
try this...
NSMutableArray *array=[[NSMutableArray alloc]initWithCapacity:50 ];
for (int i=0; i<0; i++) {
NSNumber *number=[[NSNumber alloc] initWithInt:i];
[array addObject:number];
[number release];
}
//do anything with arrray and release the array later.
is this OK or you are seeking anything else.?
How about using NSMutableArray?
NSMutableArray* arr = [[NSMutableArray alloc] init];
int i = 0;
for(i=0; i<50; i++) {
NSNumber* num = [NSNumber numberWithInt:i]; // use i or random numbers
[arr addObject:num];
}
Your numbers do not seem to follow any particular pattern, so you might be better doing this by creating a C array first:
int myValues[] = { 10, 212, ..., 12 };
NSUInteger count = sizeof(myValues)/sizeof(int); // number of integers in myValues
// abstract the following into a function/method/category if doing more than once
NSMutableArray *objcValues = [NSMutableArray arrayWithCapacity:count];
for(NSUInteger ix = 0; ix < count; ix++)
[objcValues addObject:[NSNumber numberWithInt:myValues[ix]];

How to locate maximum value and position in NSMutableArray

I need to search a mutable array for the maximum value and return its position as well as value. I'd only like to iterate through the array once and I'm not sure if that's possible
an example of what I'm trying to accomplish can be demonstrated below
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i = 0; i<20; i++)
[array addObject:[NSNumber numberWithInteger:(arc4random()%200)]];
NSObject *max = [array valueForKeyPath:#"#max.self"];
the max object only seems to contain the value (and not the position). this can be demonstrated through the debugger with print-object max
Any advice out there?
Using valueForKeyPath:#"#max.self" is great, but only if you want the maximum value.
To know both index and value in one iteration, I'd use enumerateWithBlock:
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i = 0; i<20; i++)
[array addObject:[NSNumber numberWithInteger:(arc4random()%200)]];
__block NSUInteger maxIndex;
__block NSNumber* maxValue = [NSNumber numberWithFloat:0];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSNumber* newValue = obj;
if ([newValue isGreaterThan:maxValue]) {
maxValue = newValue;
maxIndex = idx;
}
}];
Quite more code, but you're iterating only once in the array.
If you're not worried about the possibility of there being more than one identical maximum value in the array, you can use -indexOfObject: to get the index. It will return the first occurrence of the object in the array.
NSUInteger index = [array indexOfObject:max];
I hope, following solution will help you to identify maximum value from array.
int max = [[numberArray valueForKeyPath:#"#max.intValue"] intValue];
NSLog(#"Highest number: %i",max);
Please let me know if any issue.
Here you can find correct way to deal with collections and KVC
Its nice Post by Matt
http://nshipster.com/kvc-collection-operators/

Create multiple numbered variables based on a int

How would I create a number of NSDictionary variables using an array's count?
This is basically what I came up with, but I'm not sure how to make this work with Objective-C syntax. doesntContainAnother is an NSArray. I want the names of the dictionaries to use the current value of loopInt.
int *loopInt = 0;
while (doesntContainAnother.count <= loopInt) {
NSMutableDictionary *[NSString stringWithFormat:#"loopDictionary%i", loopInt] = [[[NSMutableDictionary alloc] init] autorelease];
[NSString stringWithFormat:#"loopDictionary%i", loopInt] = [NSDictionary dictionaryWithObject:[array1 objectAtIndex:loopInt]
forKey:[array2 objectAtIndex:loopInt]];
loopInt = loopInt + 1;
}
Create a mutable array and loop until you reach the original array's count, creating a dictionary and adding it to the mutable array on each iteration.
Your code should look like this.
NSMutableArray *dictionaries = [[NSMutableArray alloc] init];
for (int i = 0; i < doesntContainAnother.count; i++) {
[dictionaries addObject:[NSMutableDictionary dictionaryWithObject:[array1 objectAtIndex:i] forKey:[array2 objectAtIndex:i]]];
}
The approach of creating variables with numbers at the end of their names is an antipattern and not even possible in Objective-C. It's equivalent to an array, but clunkier.
You need to create a mutable array, and then put the objects into the array. You can't create a variable with the same name as the contents of a string, as you have done. For example:
NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:[doesntContainAnother count]];
int i = 0; // Note: type is int, not int*
for (i = 0; i < [doesntCountainAnother count]; i++) {
[arr addObject:[NSMutableDictionary dictionary]];
}
// Later...
NSMutableDictionary *d1 = [arr objectAtIndex:3];
Or if you want to pull them out of the list by name:
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:[doesntCountainAnother count]];
int i = 0;
for (i = 0; i < [doesntContainAnother count]; i++) {
[dict setObject:[NSMutableDictionary dictionary] forKey:[NSString stringWithFormat:#"loopDictionary%d", i]];
}
// Later...
NSMutableDictionary *d1 = [dict objectForKey:#"loopDictionary3"];
But the first way is likely the easiest.