add data to NSMUtableArrray with keys by for loop - iphone

I'm new in iPhone, I want to add elements to NSMutableArray with each element's name
I created a MutableArray for keys , then other array for elements that I get them from object called Pages.
I wrote the following code
NSMutableArray *myArray;
NSMutableArray *arrayKey = [[NSMutableArray alloc] initWithObjects:#"b_pag_id", #"b_pag_bo_id", #"b_pag_num", #"b_pag_note", #"b_page_mark", #"b_page_stop", #"b_pag_user_id", nil];
for (int x=0; x<[pages count]; x++) {
Pages *myPages = (Pages *)[self.pages objectAtIndex:x];
NSString *b_pag_id2 = [NSString stringWithFormat:#"%d",myPages.b_pag_id];
NSString *b_pag_bo_id2 = [NSString stringWithFormat:#"%d",myPages.b_pag_bo_id];
NSString *b_pag_num2 = [NSString stringWithFormat:#"%d",myPages.b_pag_num];
NSString *b_pag_note2 = myPages.b_pag_note;
NSString *b_page_mark2 = [NSString stringWithFormat:#"%d",myPages.b_page_mark];
NSString *b_page_stop2 = [NSString stringWithFormat:#"%d",myPages.b_page_stop];
NSString *b_pag_user_id2 = [NSString stringWithFormat:#"%d",myPages.b_pag_user_id];
NSMutableArray *arrayValue = [[NSMutableArray alloc] initWithObjects:b_pag_id2, b_pag_bo_id2, b_pag_num2, b_pag_note2, b_page_mark2, b_page_stop2, b_pag_user_id2, nil];
NSDictionary *theReqDictionary = [NSDictionary dictionaryWithObjects:arrayValue forKeys:arrayKey];
myArray = [NSMutableArray arrayWithObjects:theReqDictionary,nil];
}
NSLog(#"array size: %d", [myArray count]);
I want to add every element to its key for example
element (b_pag_id2) its key (b_pag_id) ..etc
is this right ?? or how to do this ??
consider that NSLog(#"array size: %d", [myArray count]); gives me 1 and the size of my elements is 14

Before the loop you need to initialize the aray
NSMutableArray *myArray = [NSMutableArray array];
Inside the loop replace following:
myArray = [NSMutableArray arrayWithObjects:theReqDictionary,nil];
with
[myArray addObject:theReqDictionary];
The problem is that you are creating a new array with 1 dictionary in every loop iteration. Instead you need to initialize the array and add values one by one.

Each time through your loop you are creating a new array for myArray that has only one element. You should initialize an empty NSMutableArray before the loop and then simply add your new object to it instead of using arrayWithObjects: to create myArray..

Here i'm giving a short example, and i hope this will help you.
see this code :-
NSMutableArray *arrayValue = [[NSMutableArray alloc]initWithObjects:#"Value1",#"Value2",#"Value3", nil];
NSMutableArray *arrayKey = [[NSMutableArray alloc]initWithObjects:#"1",#"2",#"3", nil];
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
for(int i=0;i<3;i++)
{
[dic setObject:[arrayValue objectAtIndex:i] forKey:[arrayKey objectAtIndex:i]];
}
//and you can see this by printing it using nslog-
NSLog(#"%#",[dic valueForKey:#"1"]);
Thank you!!!

Related

keys values in array like array[0] and so on

I am using this code
NSDictionary *yourDictionary;
NSArray * yourKeys;
yourKeys = [yourDictionary allValues];
to get the value of dictionary. But i want that array output in this form : array[0] ,array[1] while I am getting the output in console as below:-
2013-01-12 18:44:10.213 Birthday_Reminder[2871:c07] (
{
},
"Arpit Sihare")
and so on values.
so plz help me to get those values in this form and also I'm using KABPersonfirstnameproperty to retrieve those name from address book.
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *thePeople = (NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSMutableArray* allPeoplesDicts = [NSMutableArray array];
for (id person in thePeople)
{
ABMultiValueRef phone =(NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString* name = (NSString *)ABRecordCopyCompositeName(person);
// NSMutableArray* phones = [[NSMutableArray alloc] init];
NSDictionary *phones=[[NSDictionary alloc]init ];
for (CFIndex i = 0; i < ABMultiValueGetCount(phones); i++)
{
NSString *phone = [(NSString *)ABMultiValueCopyValueAtIndex(phones,i) autorelease];
[phones addObject:phone];
}
NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys:name,#"Name",phones,#"PhoneNumbers",nil];
[phones release];
NSArray * yourKeys;
yourKeys = [personDict allValues];
NSLog(#"%#",yourKeys);
[allPeoplesDicts addObject:personDict];
[personDict release];
}
and I want firstname in array form that when i use nslog(#"%#",array[0]) it should print value stored in array first place and soon like array[1]....
It's too hard to understand what you are trying to say. I tried and found...
If you just want to store all the firstName (which is your key I think) then just make yourKeys an NSMutableArray and add the names to that Array. :
[yourKeys addObject:names];
Simple !!

Convert NSMutableArray to NSDictionary in order to use objectForKey?

I have an NSMutableArray that looks like this
{
"#active" = false;
"#name" = NAME1;
},
{
"#active" = false;
"#name" = NAME2;
}
Is there a way to convert this to an NSDictionary and then use objectForKey to get an array of the name objects? How else can I get these objects?
There is a even shorter form then this proposed by Hubert
NSArray *allNames = [array valueForKey:#"name"];
valueForKey: on NSArray returns a new array by sending valueForKey:givenKey to all it elements.
From the docs:
valueForKey:
Returns an array containing the results of invoking
valueForKey: using key on each of the array's objects.
- (id)valueForKey:(NSString *)key
Parameters
key The key to retrieve.
Return Value
The value of the retrieved key.
Discussion
The returned array contains NSNull elements for each object that returns nil.
Example:
NSArray *array = #[#{ #"active": #NO,#"name": #"Alice"},
#{ #"active": #NO,#"name": #"Bob"}];
NSLog(#"%#\n%#", array, [array valueForKey:#"name"]);
result:
(
{
active = 0;
name = Alice;
},
{
active = 0;
name = Bob;
}
)
(
Alice,
Bob
)
If you want to convert NSMutableArray to corresponding NSDictionary, just simply use mutableCopy
NSMutableArray *phone_list; //your Array
NSDictionary *dictionary = [[NSDictionary alloc] init];
dictionary = [phone_list mutableCopy];
This is an Array of Dictionary objects, so to get the values you would:
[[myArray objectAtIndex:0]valueForKey:#"name"]; //Replace index with the index you want and/or the key.
This is example one of the exmple get the emplyee list NSMutableArray and create NSMutableDictionary.......
NSMutableArray *emloyees = [[NSMutableArray alloc]initWithObjects:#"saman",#"Ruchira",#"Rukshan",#"ishan",#"Harsha",#"Ghihan",#"Lakmali",#"Dasuni", nil];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *word in emloyees) {
NSString *firstLetter = [[word substringToIndex:1] uppercaseString];
letterList = [dict objectForKey:firstLetter];
if (!letterList) {
letterList = [NSMutableArray array];
[dict setObject:letterList forKey:firstLetter];
}
[letterList addObject:word];
} NSLog(#"dic %#",dict);
yes you can
see this example:
NSDictionary *responseDictionary = [[request responseString] JSONValue];
NSMutableArray *dict = [responseDictionary objectForKey:#"data"];
NSDictionary *entry = [dict objectAtIndex:0];
NSString *num = [entry objectForKey:#"num"];
NSString *name = [entry objectForKey:#"name"];
NSString *score = [entry objectForKey:#"score"];
im sorry if i can't elaborate much because i am also working on something
but i hope that can help you. :)
No, guys.... the problem is that you are stepping on the KeyValue Mechanism in cocoa.
KeyValueCoding specifies that the #count symbol can be used in a keyPath....
myArray.#count
SOOOOOO.... just switch to the ObjectForKey and your ok!
NSMutableDictionary *myDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"theValue", #"#name", nil];
id kvoReturnedObject = [myDictionary valueForKey:#"#name"]; //WON'T WORK, the # symbol is special in the valueForKey
id dictionaryReturnedObject = [myDictionary objectForKey:#"#name"];
NSLog(#"object = %#", dictionaryReturnedObject);

Array in UITextView

I have an arrayappdeligate.biblearray. I just want to display this array in a textview. This array contains sql datas of 4 types chapterno, verses, genisis and text. i need to extract only the verses and display it in textview how to do this?
It seems biblearray has the objects of type bible. You can get the verses from bible objects like this,
bible *_bible = (bible *)[appDelegate.bibleArray objectAtIndex:0];
textView.text = [_bible verses];
or directly as,
textView.text = [[appDelegate.bibleArray objectAtIndex:0] verses];
If you want to display all the verses in the textView, you can do it like this,
NSArray *allVerses = [appDelegate.bibleArray valueForKey:#"verses"];
textView.text = [allVerses componentsJoinedByString:#"\n\n"];
#"\n\n" adds two new lines between the verses.
You need to do some alteration. Create NSDisctionary instead.
Take a dictionary where you are adding data from database
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
NSMutableArray *chapterno = [[NSMutableArray alloc]init];
NSMutableArray *verses = [[NSMutableArray alloc]init];
NSMutableArray *genisis = [[NSMutableArray alloc]init];
NSMutableArray *text = [[NSMutableArray alloc]init];
//Add data you are getting from database
[chapterno addObject:chapternodata];
[verses addObject:versesdata];
[genisis addObject:genisisdata];
[text addObject:textdata];
[dict setValue:chapterno forKey:#"chapterno"];
[dict setValue:verses forKey:#"verses"];
[dict setValue:genisis forKey:#"genisis"];
[dict setValue:text forKey:#"text"];
[chapterno release];
[verses release];
[genisis release];
[text release];
Take one NSDictionary in AppDelegate say appDict and make it equal to dict
NSMutableArray *arrVerses = [[objAppDel.appDict objectForKey:#"verses"];
txt.text = [arrVerses description];

how to create an array of string or float in Objective-C

i need some help here, i need to know how to create an array of string retrieved from an array. i'm using powerplot for graph and it only accept float or string array.
i need to create something something like this dynamically.
NSString * sourceData[7] = {#"2", #"1", #"4", #"8", #"14", #"15", #"10"};
Below are my code to find out the numbers in strings.
NSInteger drunked = [appDelegate.drinksOnDayArray count];
NSMutableArray * dayArray = [[NSMutableArray alloc] init];
NSMutableArray * sdArray = [[NSMutableArray alloc] init];
//float *sdArray[7];
for (int i=0; i<drunked; i++) {
DayOfDrinks *drinksOnDay = [appDelegate.drinksOnDayArray objectAtIndex:i];
NSString * dayString= [NSDate stringForDisplayFromDateForChart:drinksOnDay.dateConsumed];
[dayArray addObject:dayString];
NSLog(#"%#",[dayArray objectAtIndex:i]);
drinksOnDay.isDetailViewHydrated = NO;
[drinksOnDay hydrateDetailViewData];
NSString * sdString= [NSString stringWithFormat:#"%#", drinksOnDay.standardDrinks];
[sdArray addObject:sdString];
NSString *tempstring;
NSLog(#"%#",[sdArray objectAtIndex:i]);
}
thanks for the help :)
Array's in Objectice-C aren't that hard to work with:
NSMutableArray *myArray = [NSMutableArray array];
[myArray addObject:#"first string"]; // same with float values
[myArray addObject:#"second string"];
[myArray addObject:#"third string"];
int i;
int count;
for (i = 0, count = [myArray count]; i < count; i = i + 1)
{
NSString *element = [myArray objectAtIndex:i];
NSLog(#"The element at index %d in the array is: %#", i, element); // just replace the %# by %d
}
You can either use NSArray or NSMutableArray - depending on your needs, they offer different functionality.
Following tutorial covers exactly what you are looking after:
http://www.cocoalab.com/?q=node/19
You can also add the elements to the array when you init (and optionally add them later only if you are using the Mutable version of a collection class:
NSMutableArray *myArray = [[NSMutableArray alloc] initWithObjects:#"2", #"1", #"4", #"8", #"14", #"15", #"10", nil];
[myArray addObject:#"22"];
[myArray addObject:#"50"];
//do something
[myArray release];
You can use malloc to create a C-style array. something like this should work:
NSString **array = malloc(numElements * sizeof(NSString *))
some code here
free(array)
Be aware that unlike NSMutable array, c arrays won't do a retain, so you have to manage it if needed. And don't forget the free

Joining all the elements in an NSMutableArray to form an NSString

I have an NSMutableArray of NSString objects. How would I make an NSString that consists of all the elements in that array joined together with semicolons in between?
For example:
array = "hello","hi","bye",nil;
output = "hello;hi;bye";
NSMutableArray *array = [NSMutableArray arrayWithObjects:#"hello", #"hi", #"bye", nil];
NSString *output = [array componentsJoinedByString:#";"];