I am working on a project where I download a few values (stored as float in my database) into my array and sum them. I can NSLog the numbers but Unfortunately I am having the hardest time to sum those values in my array.
Adding some code
DETAILS.H
#import <Foundation/Foundation.h>
#interface Details: NSObject
#property (nonatomic, strong)NSNumber *min;
//#property (nonatomic, strong) NSString *min;
#end
just the part of the code where I put the values in the array
for (int i = 0; i < jsonArray.count; i++)
{
NSDictionary *jsonElement = jsonArray[i];
tempDetails *downloadTemps = [[tempDetails alloc] init];
downloadTemps.min = jsonElement[#"min"];
// Add this question to the locations array
[_locations addObject:downloadTemps];
}
View controller code
for (Details *sav in _importArray )
{
NSLog(#"High :- %# ", sav.min); //THIS LIST ALL MY VALUES CORRECTLY
}
NSMutableArray *newArray = [_importArray mutableCopy];
int totalSum = 0;
for(int i=0; i<[newArray count];i++)
{
totalSum = totalSum + [[newArray objectAtIndex:i] intValue];
}
NSLog(#"Total:%d",totalSum);
In the view controller I get the error
[Details intValue]: unrecognized selector sent to instance ,
I am assuming I am getting this error because min is not declared right, But I am unsure how to do it other wise. Any help offered would be appreciated.
Thank you
You are asking for the selector intValue, but you should be asking for the selector min.
totalSum = totalSum + [[[newArray objectAtIndex:i] min] intValue];
You were pretty close in the first block you posted:
for (Details *sav in _importArray )
{
NSLog(#"High :- %# ", sav.min); //THIS LIST ALL MY VALUES CORRECTLY
}
Then:
int totalSum = 0;
for (Details *sav in _importArray )
{
totalSum += [sav.min intValue];
}
Incidentally, why are you asking for the intValue of something that you initially wrote was a float?
Related
This question already has answers here:
Sorting two NSArrays together side by side
(4 answers)
Closed 6 years ago.
I have 2 NSMutableArrays declared. One is filled with names and then another one is filled with string values of NSDate.
I want to sort both of them according to the date in the second one. For example if element 3 in the date array becomes element 0 I want the same to happen for the name array.
What is the easiest way to do this? I know how to sort the date array just not the corresponding name array!
(Objective-C Please!)
Sorting 2 arrays and keeping them in sync is a pain. You basically have to sort them by hand.
Probably the easiest way to do this is to create an array of dictionaries where each dictionary contains a data and a name.
Then sort the array of dictionaries by date.
EDIT:
Here is the code for creating custom objects containing a name and a date. There is code to sort by date as well as code to sort by name:
/**
The thing class has a property date and a property name.
It is purely for creating sorted arrays of objects
*/
#interface Thing : NSObject
#property (nonatomic, strong) NSDate *date;
#property (nonatomic, strong) NSString *name;
#end
#implementation Thing
/**
This is a dummy init method that creates a Thing ojbect with a random name and date
*/
- (instancetype) init {
self = [super init];
if (!self) return nil;
NSString *letters = #"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
NSMutableString *temp = [NSMutableString new];
for (int x = 0; x < 10; x++) {
unichar aChar = [letters characterAtIndex:arc4random_uniform(26)];
[temp appendFormat: #"%C", aChar];
}
self.name = [temp copy];
//Create a random date
uint32 halfMax = 2000000000;
uint32 max = halfMax * 2;
int32_t value = arc4random_uniform(max) - halfMax;
NSTimeInterval now = [[NSDate date] timeIntervalSinceReferenceDate];
self.date = [NSDate dateWithTimeIntervalSinceReferenceDate: now + value];
return self;
}
- (NSString *) description {
return [NSString stringWithFormat: #"Name: %# Date: %#", self.name, self.date];
}
#end
int main(int argc, const char * argv[]) {
#autoreleasepool {
//Create an array of Thing objects
const int count = 50;
NSMutableArray *thingArray = [NSMutableArray arrayWithCapacity: count];
for (int x = 0; x < count; x++) {
thingArray[x] = [[Thing alloc] init];
}
#if 1
//Sort by date, ascending
[thingArray sortUsingComparator:^NSComparisonResult(Thing *obj1,
Thing *obj2) {
NSComparisonResult bigger =
[obj1.date timeIntervalSinceReferenceDate] <
[obj2.date timeIntervalSinceReferenceDate] ?
NSOrderedAscending : NSOrderedDescending;
return bigger;
}];
#else
//Sort by name
[thingArray sortUsingComparator:^NSComparisonResult(Thing *obj1,
Thing *obj2) {
return [obj1.name compare: obj2.name];
}];
#endif
NSLog(#"%#", thingArray);
}
return 0;
}
Say I have n variables
NSNumber* A = #(1);
NSNumber* B = #(2);
NSNumber* C = #(3);
NSNumber* D = #(4);
NSNumber* E = #(5);
...
I need a dictionary like
{#"A":#(1), #"B":#(2), #"C":#(3), #"D":#(4), ... }
One can imagine a more cumbersome example that would be tedious to type out
I think saw a C style function for it but I can't remember. Something like NSDictionaryForVariables()
The C preprocessor macro (not a function) you're looking for is NSDictionaryOfVariableBindings. However, outside of Auto Layout (and, debatably, even there), it's not really a great idea to be setting up dependencies between runtime and compile-time identifiers like that.
Depending on what you're trying to actually accomplish, Key-Value Coding might be a better solution.
It's not a good approach you may find another way to solve your issue but if you want to have an idea about your requested solution here here my try
Our properties
#interface TestyViewController ()
#property (nonatomic) NSNumber* a;
#property (nonatomic) NSNumber* b;
#property (nonatomic) NSNumber* c;
#property (nonatomic) NSNumber* d;
#end
Set the values
- (void)viewDidLoad {
[super viewDidLoad];
self.a=#(1);
self.b=#(2);
self.c=#(3);
self.d=#(4);
}
Get our instance variables
-(NSArray *)propertyNames{
unsigned int propertyCount = 0;
objc_property_t * properties = class_copyPropertyList([self class], &propertyCount);
NSMutableArray * propertyNames = [NSMutableArray array];
for (unsigned int i = 0; i < propertyCount; ++i) {
objc_property_t property = properties[i];
const char * name = property_getName(property);
[propertyNames addObject:[NSString stringWithUTF8String:name]];
}
free(properties);
return propertyNames;
}
Create the dictionary
- (IBAction)buttonClicked:(id)sender
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for (NSString* varName in [self propertyNames])
{
[dict setObject:[self valueForKey:varName] forKey:varName];
}
NSLog(#"%#",dict);
}
result
2015-07-15 20:30:56.546 TestC[879:27973] {
a = 1;
b = 2;
c = 3;
d = 4;
}
#property NSMutableArray*textFieldsA;
#property NSMutableArray*textFieldsB;
#property NSMutableArray*textFieldsR;
#property NSMutableArray *operandArrayA;
#property NSMutableArray *operandArrayB;
_textFieldsA = #[self.textFieldA0, self.textFieldA1, self.textFieldA2, self.textFieldA3, self.textFieldA4, self.textFieldA5, self.textFieldA6, self.textFieldA7, self.textFieldA8];
_textFieldsB = #[self.textFieldB0, self.textFieldB1, self.textFieldB2, self.textFieldB3, self.textFieldB4, self.textFieldB5, self.textFieldB6, self.textFieldB7, self.textFieldB8];
_textFieldsR = #[self.textFieldR0, self.textFieldR1, self.textFieldR2, self.textFieldR3, self.textFieldR4, self.textFieldR5, self.textFieldR6, self.textFieldR7, self.textFieldR8];
for (int i = 0; i < 9; i++) {
_operandA = [((UITextField*)_textFieldsA[i]).text integerValue];
_operandB = [((UITextField*)_textFieldsB[i]).text integerValue];
[self.arithmetic setOperandA:_operandA operandB:_operandB operator:_operator];
_finalString = [NSString stringWithFormat:#"%d",[self.arithmetic result]];
((UITextField*)_textFieldsR[i]).text = _finalString;
}
how can i put the integerValue of
self.textFieldA0.text , self.textFieldA1.text , self.textFieldA3.text ........self.textFieldA8.text
in to the array (operandArrayA)?
i have tried
operandArrayA[i] = [((UITextField*)_textFieldsA[i]).text integerValue];
but it is not work, how should i do?
Unfortunately you can not add primitive datatypes in NSArray. You need to create object of NSNumber for integer value. Store this object to an array.
Like this:
NSNumber *number = #([((UITextField*)_textFieldsA[i]).text integerValue]);
operandArrayA[i] = number;
You need to alloc and initialize all the arrays..like below
operandArrayA=[[NSMutableArray alloc]init];
operandArrayB=[[NSMutableArray alloc]init];
//if u want to store strings
[operandArrayA addObject:((UITextField*)_textFieldsA[i]).text];
[operandArrayB addObject:((UITextField*)_textFieldsB[i]).text];
//(OR) if u want to store integer value then u need to convert to NSNumber
[operandArrayA addObject:[NSNumber numberWithInt:[((UITextField*)_textFieldsA[i]).text integerValue]]];
[operandArrayB addObject:[NSNumber numberWithInt:[((UITextField*)_textFieldsB[i]).text integerValue]]];
//(OR)
operandArrayA[i]=[NSNumber numberWithInt:[((UITextField*)_textFieldsA[i]).text integerValue]];
operandArrayB[i]=[NSNumber numberWithInt:[((UITextField*)_textFieldsB[i]).text integerValue]];
Hope it helps you..
I have an NSArray with objects inside (CLLocation). I can have 50, 100, 300 or more objects inside. In fact, this array is used while the user walking and can follow a direction. But the user can start at the middle of my NSArray, you know what I mean ?
Well, I Have to loop all the time my array to know where my user is compare to the locations in my array.
My question is: Is it possible to use a thing like in Java with a "cursor" in a list, and simply call "Next object" to travel in my array instead of loop ?
Because I need that the user walk on all location of my array.
Example:
Count of my array: 100
User start at location at index 34 (the nearest location found)
The user must do 35, 36, 37... 100 AND 0,1,2,3 ... until 33.
Hope it's clear, I really don't know how to do this without using for loop...
Thank you for help and suggestions!
Regards,
Lapinou.
Here's one way:
NSArray * arr = ... yourArray
int index = [arr indexOfObject:currentLocation];
index ++;
if (index == arr.count) index = 0;
id nextLocation = arr[index];
Another might be to create a global counter variable that stores the current position. If these needs to last after the user closes the app, you could write it to user defaults
Is looks like you are want to use NSEnumerator
NSEnumerator Class Reference
NSArray *anArray = // ... ;
NSEnumerator *enumerator = [anArray objectEnumerator];
id object;
while ((object = [enumerator nextObject])) {
// do something with object...
}
try this:
#interface ArrayEnumerator : NSEnumerator
{
NSArray* array;
NSInteger index;
NSInteger startIndex;
BOOL over;
}
- (id)initWithArray:(NSArray*)anArray
atIndex:(NSInteger)anIndex;
#end
#implementation ArrayEnumerator
- (id)initWithArray:(NSArray*)anArray
atIndex:(NSInteger)anIndex
{
if (self=[super init]) {
array = anArray;
index = anIndex;
startIndex = anIndex;
over = NO;
}
return self;
}
- (id)nextObject
{
if (index == [array count]) {
index = 0;
over = YES;
}
if (over && index == startIndex)
return nil;
return array[index++];
}
- (NSArray*)allObjects
{
return array;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
NSArray* array = #[#0,#1,#2,#3,#4,#5,#6,#7,#8,#9];
id element;
ArrayEnumerator* enumerator = [[ArrayEnumerator alloc] initWithArray:array atIndex:4];
while (element = [enumerator nextObject])
NSLog(#"%#", element);
}
#end
What is wrong with a for loop?
An iterator is typically used on lists, because you can't access elements in a list by index. However you are working with an array, so you don't need an iterator, but rather some clever way of accessing the array in the desired order.
Maybe this code can provide you with some ideas. This will run from 34 to 100, then start with 0 and go up to 33.
for (int i = 34; i < 134; i++)
{
int ix = i % 100;
id whatever = arr[ix];
}
You can access array elements by index:
CLLocation * myLocation = myArray[34];
(or)
int i = 34;
CLLocation * myLocation = myArray[i];
I'm stumpped on how iterate and get values for an Array of Arrays of NSDictionaries (different classes/entities). Here's what I'm currently doing:
1) Constructing two separate arrays of NSDictionaries (different entities)
2) Combining both arrays with:
NSMutableArray *combinedArrayofDicts = [[NSMutableArray alloc] initWithObjects: sizesArrayOfDicts, wishListArrayOfDicts , nil];
3) Then archive combinedArrayofDicts :
NSData *dataToSend = [NSKeyedArchiver archivedDataWithRootObject:combinedArrayofDicts];
4) Transmit over GameKit
[self.session sendDataToAllPiers:dataToSend withDataMode: GKSendDataReliable error:nil];
5) How would I manage traversing thru this array on the receiving end? I want to fetch values by for each class which is key'ed by classname:
Here's how it looks via NSLog (2 Sizes Dicts, and 1 Wishlist Dict)
Printing description of receivedArray:
<__NSArrayM 0xbc65eb0>(
<__NSArrayM 0xbc651f0>(
{
classname = Sizes;
displayOrder = 0;
share = 1;
sizeType = Neck;
value = "13\" or 33 (cm)";
},
{
classname = Sizes;
displayOrder = 0;
share = 1;
sizeType = Sleeve;
value = "34\" or 86 (cm)";
}
)
,
<__NSArrayM 0xbc65e80>(
{
classname = Wishlist;
detail = "";
displayOrder = 0;
imageString = "";
latitude = "30.33216666666667";
link = "http://maps.google.com/maps?q=loc:30.332,-81.41";
longitude = "-81.40949999999999";
name = bass;
share = 1;
store = "";
}
)
)
(lldb)
In my for loop I'm issuing this:
NSString *value = [dict objectForKey:#"classname"];
and get an exception:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]:
unrecognized selector sent to instance 0xbc651f0'
Is this frowned upon as far as mixing object types in arrays of arrays?
#Will guided me to the answer with the right construct.. Here's the final answer:
NSArray *receivedArray;
if(receivedArray.count>0){
NSArray *combinedArrayofDicts = [receivedArray objectAtIndex:0];
if(combinedArrayofDicts.count>=2){
NSArray *sizesArray = [receivedArray objectAtIndex:0]; // Reference original received array
for(NSDictionary *sizeDict in sizesArray){
NSLog(#"%#",sizeDict);
}
NSArray *wishListArray = [receivedArray objectAtIndex:1]; // Reference original received array
for(NSDictionary *wishDict in wishListArray){
NSLog(#"%#",wishDict);
}
}
}
for fetching the required dictionaries use the following code,
Assume receivedArray as the array receive from Game center
NSArray *receivedArray;
if(receivedArray.count>0){
NSArray *combinedArrayofDicts = [receivedArray objectAtIndex:0];
if(combinedArrayofDicts.count>=2){
NSArray *sizesArray = [combinedArrayofDicts objectAtIndex:0];
for(NSDictionary *sizeDict in sizesArray){
NSLog(#"%#",sizeDict);
}
NSArray *wishListArray = [combinedArrayofDicts objectAtIndex:1];
for(NSDictionary *wishDict in wishListArray){
NSLog(#"%#",wishDict);
}
}
}
how iterate and get values for an Array of Arrays of NSDictionaries
As you said you have array of array of dictionaries, your current code will not retrive value of class name.
Your return values are in NSArray not in NSDictionary
So you need to do something like,
NSString *value = [returnArray[0][0] objectForKey:#"classname"];
You can iterate and get values like,
for (int i = 0; i < [returnArray count]; i++) {
for (int j = 0; j < [returnArray[i] count]; j++) {
NSDictionary *dict = (NSDictionary*)returnArray[i][j];
NSLog(#"%# ...",[dict objectForKey:#"classname"]);
}
}
Perhaps you can try:
NSString *value = [NSString stringWithFormat:#"%#",[dict objectForKey:#"classname"]];
By the looks of your output, I don't think "Sizes" is a string.