read int dynamically in array - iphone

I have values i wanted to load dynamically in an array, here are the examples
First of all i define 3 different values in my init, and then in my array i want it to determine which value to read. Example:
First i define the value
int value1=20
int value2=40;
int value3=60;
i then define another int in my array called valueToLoad, and i'll give each of them a number tag. and i want the individual array item to read different value based on their number tag so that Item 1 will read value1, Item 2 will read value2 and so on. i tried the method below to convert NSString into int:
NSString *valueVariable=[NSString stringWithFormat:#"value%d",i]; (i being the number tag)
int valueToRead = [valueVariable intValue];
unfortunately, this conversion doesn't supports conversion of any other thing except if the string is actual integer.
However i do not want to run the IF statement to do:
if(tag==1)
{ int valueToLoad= value1;}
For who don't understand. I am just trying to read different Int value in an array based on the number of array. Let's assume i have 3 Items in array naming A,B,and C. i want Item A to read Value 1, ItemB to read Value2 and so on.

Why don't you simply do something like
int values[] = {20,40,60};
...
int valueToRead = values[i]; //or i-1, depending if i starts from 0 or 1
?

Not sure about the context of your problem but why don't you use an NSDictionary?
That way you can store your number tag as the key and your value to read as the value...
You fill your dictionary like this:
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:value1, tag1, value2, tag2, nil];
Read your value using : [dict objectForKey:tag1];

You can use an array, store your variables in there, and index into it.
You can use a dictionary, store your variables as values, and look them up by key.
You can declare all your variables as #property, and then use [self valueForKey:] to look them up by name.
You can build the name of the ivar as a string, and then use something like object_getInstanceVariable() to retrieve it's value directly (this is similar to #3, except you don't have to declare it as an #property).
If you're dealing with views, you can assign each view a unique tag and then retrieve it via [superview viewWithTag:aTag].
EDIT: Note that this only works with instance variables. This does not work with global/static variables.
took from: Objective C Equivalent of PHP's "Variable Variables"

Related

int++ increments by 4

Here's my code:
- (IBAction)NextTouched:(id)sender {
NSLog(#"Index = %i", index);
if([project getCount]>(index++)) {
[self setUI:index];
}
}
Index is an integer, as declared in my .h file:
#property (nonatomic) int *index;
But every time I click the button, the log says the integer is going up by 4. Can you tell my why?
The reason it's going up by 4 is because index is a pointer. When you increment a pointer its value increases by the size of the data type it points to, in this case an int, which is 4 bytes.
Given index appears to be an index into an NSArray (or some other collection class), I think you want to make it int and not int * to solve your issue. Better still make it unsigned, like NSUInteger, which is the type returned from the count method.
Also I think you'll want to use prefix-increment rather than postfix-increment so that the if test uses the newly incremented value, not the previous value.
Simply define index as an integer variable rather than pointer and if you want to print the value before increment use index++ else use ++index to increment the value and then print

How to get the largest value from NSArray containing dictionaries?

How do you get the largest value from an NSArray with dictionaries?
Lets say I have NSArray containing dictionaries with keys "age", "name", etc.
Now I want to get the record with the highest age.
Is this possible with some KVC magic? Or do I have to iterate through and do it the "manual" way?
I've tried with something similar to this:
int max = [[numbers valueForKeyPath:#"#max.intValue"] intValue];
Unless "intValue" is a key in your dictionary the key path won't do much good.
If it is the max age you are after you should use #"#max.age" (on the dictionary) to get it. The same goes for any other key in your dictionary.
[myDictionary valueForKeyPath:#"#max.age"];
If numbers is an array of values you could use #"#max.self" as the key path to get the largest value.
[myArrayOfNumbers valueForKeyPath:#"#max.self"];
You're nearly there, you just need to specify the exact field you want from which you want the max value:
NSInteger max = [[numbers valueForKeyPath:#"#max.age"] integerValue];
I took the liberty to modify your ints to NSIntegers, just in case somebody wants to use this code on both iOS and OS X.

iphone - Create NSMutableDictionary filled with NSMutableArrays dynamically

I have an array of objects. Each object has property "date" and "title".
I want to populate sectioned UITableView with those items like:
Section 1 - 2012.06.12 (taken from object.date)
Cell 1.1: Title 1 (taken from object.name)
Cell 1.2: Title 2
Cell 1.3: Title 3
...
Section 2 - 2012.06.13
Cell 2.1: Title 1
Cell 2.2: Title 2
..
Section 3 ..
I can do that by manually creating 1..n NSMutableArrays for all date combinations and filling them with object.name values. But the problem is I do not know how many date combinations there are, so it should be done dynamically. Also, the date property can repeat in different objects
My object structure is:
Object
-NSDate - date
-NSString - title
UPD:
I was thinking if it is possible to create NSDictionary, where the key would be my date and the object would be NSArray, which contains all my items for the key-date. But I do not know how to do that dynamically.
I hope I explained my question clearly enough.
Thank you in advance!
You can create arrays based on date.You have array of objects, so iterate through this array of objects to get distinct dates, as follows:
for(int i =0;i<[objectsArr count];i++)
{
if(![newDateArr containsObject:[objectsArr objectAtIndex:i].date])
{
[newDateArr addObject:[objectsArr objectAtIndex:i].date];
}
NSMutableArray *newTitleArray = [newTitleDictionary objectForKey:#"[objectsArr objectAtIndex:i].date"];
if(newTitleArray != nil)
{
[newTitleArray addObject:[objectsArr objectAtIndex:i].title];
}
else
{
newTitleArray = [[[NSMutableArray alloc] init] autorelease];
[newTitleArray addObject:[objectsArr objectAtIndex:i].title];
}
[newTitleDictionary setValue:newTitleArray forKey:#"[objectsArr objectAtIndex:i].date"];
}
where newTitleDictionary and newDateArr are declare outside this method.Now you can use both is newTitleDictionary and newDateArr to populate tableview.
If I understand you correctly, you want to put an object into an array and then use that array to populate a table view?
Just add the date object each time to the NSMutableArray.
[myArray addObject:dateObject];
Then when it comes to populating the table view..
DateObject *newDateObj = [myArray objectAtIndex:index];
I hope this helps and I understood your question
EDIT To answer now I understand a bit more.
Step 1
Check through the existing array of dates and see if there are any that match maybe by iterating through it using a for loop. Search online for how to compare NSDate.
Step 2 If it doesn't match any then insert it into the array as an array with just that date on it's own so the array count will be one. If it does match then insert it into the array along with that one making the array count 2 or more.
Step 3 When it comes to declaring the section amount for the table just return the dateHolderArray count.
Step 4 When declaring the amount of rows in each section, return the array count for the array thats inside the dateHolderArray.
Step 5 Display the content when it comes to populating the cells with information. It becomes just a task of getting the dates from the arrays using the section ids and row ids.
This is how I would do it, there are probably many other methods. Any questions just ask

Getting length of an array inside a Dictionary Key

I'm sure this is a very obvious question but I'm not getting anywhere with it and I've been trying for half an hour or so now.
I have an NSMutableDictionary which has keys & values, obviously. Each key stores an array of objects. What I need to do is find a specific array in a key and get the list of the array. The catch is that I don't know the value of the key, I just know it's index. (EG: I know I need to find the array in the 2nd key).
I am almost certain this is a very easy & trivial thing to do but it's escaping me, I've only been doing Obj-C for a short while so not entirely at home with it yet!
Thanks,
Jack.
Use allKeys: to access the keys of your dictionary.
- (NSArray *)allKeys
Use as below .
NSArray* dictAllKeys = [dict allKeys];
if([dictAllKeys count] > 2)
{
NSArray* myArrayInDict = [dict objectForKey:[dictAllKeys objectAtIndex:1]];
// get the length of array in dict at 2nd key
int length = [myArrayInDict count];
}
The order will probably change if another key/value pair is added, it is a NSMutableDictionary. It is best not to rely on the order of a NSDictionary or NSSet.
Suggestion: Either use another container that does provide ordering such as NSMutableArray or find the item using the dictionary's value arrays, perhaps with NSPredicate.

Objective-C, How can I produce an array / list of strings and count for each?

My aim is to produce an array, which I can use to add section headers for a UITableView. I think the easiest way to do this, is to produce a sections array.
I want to create section headers for dates, where I'll have several or no rows for each.
So in my populate data array function, I want to populate a display array. So record 1, look for the first date in my display array, create a new array item if it doesn't exist, if it does exist add 1 to the count.
So I should end up with something like this.
arrDisplay(0).description = 1/June/2001; arrDisplay(0).value = 3;
arrDisplay(1).description = 2/June/2001; arrDisplay(1).value = 0;
arrDisplay(2).description = 3/June/2001; arrDisplay(2).value = 1;
arrDisplay(3).description = 5/June/2001; arrDisplay(3).value = 6;
My question is how do I create and use such an array with values, where I can add new elements of add to the count of existing elements and search for existing elements ?
I think, if i understand you, an NSMutableDictionary would work. (as NR4TR said) but, i think the object would be the description and the key would be the count. you could check for the key and get the count in the same gesture. if the return value of objectForKey is nil, it doesn't exist.
NSMutableDictionary *tableDictionary = [[NSMutableDictionary alloc] init];
NSString *displayKey = #"1/June/2001";
NSNumber *displayCount = [tableDictionary objectForKey:displayKey];
if (displayCount != nil) {
NSNumber *incrementedCount = [[NSNumber alloc] initWithInteger:[displayCount integerValue] + 1];
[tableDictionary removeObjectForKey:displayKey];
[tableDictionary setValue:incrementedCount
forKey:displayKey];
[incrementedCount release];
}
else {
NSNumber *initialCount = [[NSNumber alloc] initWithInteger:1];
[tableDictionary setValue:initialCount
forKey:displayKey];
[initialCount release];
}
EDIT: Hopefully this isn't pedantic, but I think a couple pointers will help.
Dictionaries, Sets, and Arrays all hold objects for retrieval. The manner of holding and retrieval desired drives the decision. I think of it based on the question 'what is the nature of the information that I have when I need an object being held?'
NSDictionary and NSMutableDictionary
Hold n objects per key. (I think...I haven't had to test a limit, but i know you can get an NSSet back as a value.)
KEY is more important than INDEX. I don't think of dictionaries as ordered. they know something and you need to ask the correct question.
NSArray and NSMutableArray
hold n objects in order.
INDEX is most important bit of information. (you can ask for the index of an object but, even here, the index is the important part)
you will typically drive table views with an array because the ordered nature of the array fits.
NSSet, NSMutableSet, and NSCountedSet
A collection of objects without order.
You can change any of these into the other with something like [nsset setFromArray:myArray];
and all of these things can hold the other as objects. I think an array as your top level is the correct thinking, but beyond that, it becomes an issue of implementation
Try array of dictionaries. Each dictionary contains two objects - section title and array of section rows.
If you want to have a description AND a rowcount then you can either create a class with those two properties and generate an NSArray of objects with that class or instead of all that you can just use an NSDictionary to store key/value lookups.
I think NSCountedSet is closest to what you want. It doesn't have an intrinsic order, but you can get an array out of it by providing a sort order.