Using FlurryAnalytics logEvent:withParameters - ios5

When a user enters a search query, I'd like to track:
1) Their search term
2) Number of results returned
3) CFUUID
Can someone tell me if all of these parameters can be put into 1 Dictionary or do I need to create a separate Dictionary for every key/value?
Can I do this:
NSDictionary *flurryDict =
[NSDictionary dictionaryWithObjectsAndKeys:searchText,#"Search Term",numResults,#"Results Returned",nil];
[FlurryAnalytics logEvent:#"USER_SEARCH" withParameters:flurryDict];
Here's what I have so far:
//View Controller
if([searchText length] >=3){
NSLog(#"Search: %#",searchText);
NSLog(#"Search Results: %i",[self.filteredListContent count]);
NSLog(#"Device UUID: %#",[sharedLabelManager myUUID]);
//Send to Flurry
NSDictionary *flurryDict =
[NSDictionary dictionaryWithObjectsAndKeys:#"Search Term", searchText, nil];
[FlurryAnalytics logEvent:#"SEARCH" withParameters:flurryDict];
}

Yep. Dictionaries are a set of keys and values, something like below will work just fine:
NSString *uuid = [sharedLabelManaged myUUID];
NSNumber *totalResults = [NSNumber numberWithInt:self.filteredListContent.count];
NSDictionary *flurryDict = [NSDictionary dictionaryWithObjectsAndKeys:searchText, #"SearchTerm", totalResults, #"SearchResultsCount", uuid, #"UUID", nil];
[FlurryAnalytics logEvent:#"SEARCH" withParameters:flurryDict];

Related

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);

How to add the object array to nsmutabledictionary with another array as key

for(Attribute* attribute in appDelegate.attributeArray) {
attribute = [appDelegate.attributeArray objectAtIndex:z];
attri = attribute.zName;
int y = 0;
for(Row* r in appDelegate.elementsArray) {
r = [appDelegate.elementsArray objectAtIndex:y];
NSString *ele = r.language;
if([attri isEqualToString:ele]) {
NSLog(#"=================+++++++++++++++++%# %#",attri, r.user);
[aaa insertObject:r atIndex:y]; //here i am adding the value to array
[dict setObject:aaa forKey:attri]; //here i am adding the array to dictionary
}
y++;
}
z++;
NSLog(#"============$$$$$$$$$$$$$$$$$$$$$$$++++++++++ %#",dict);
}
key in one array and the value in the another array and the value array is in object format.
I need to store the multi object for the single key. The attributeArray has the key value and the elementsArray has the object. For example the attributeArray might have the values
" English, French, German..."
and the elementsArray might have the object value
"<Row: 0x4b29d40>, <Row: 0x4b497a0>, <Row: 0x4e38940>, <Row: 0x4b2a070>, <Row: 0x4b29ab0>, <Row: 0x4b178a0> "
In the first value I need to store the two object and for second key I need to store 3 objects and for the third key in need to store last two objects in the dictionary.
For super-simplification you can use the following code:
NSArray *keys = ...;
NSArray *values = ...;
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjects: values forKeys: keys];
Hope, this helps.
UPDATE:
to store multiple values for single key in the dictionary, just use NSArray / NSMutableArray as your object:
NSArray *keys = ...;
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for( id theKey in keys)
{
NSMutableArray *item = [NSMutableArray array];
[item addObject: ...];
[item addObject: ...];
...
[dict setObject: item forKey: theKey];
}
If you don't know all the values for the key from the beginning and need to add them one by one, you can use the following approach:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for( /*some cycling condition here */)
{
id keyToUse = ...;
id valueToAdd = ...;
id foundArray = [dict objectForKey: keyToUse];
if ( nil == foundArray )
{
foundArray = [NSMutableArray array];
[dict setObject: foundArray forKey: keyToUse];
}
[foundArray addObject: valueToAdd];
}
To me it looks you are settings an array (aaa) with string (attri) as a key.
To set an array as a key for another array as an object. You can do this with the following appraoch.
NSMutableDictionary *myDictionary = [NSMutableDictionary dictionaryWithCapacity:1];
NSArray *valueArray = [NSArray arrayWithObjects:#"v1", #"v2", nil];
NSArray *keyArray = [NSArray arrayWithObjects:#"k1",#"k2", nil];
[myDictionary setObject:valueArray forKey:keyArray];
NSLog(#"myDictionary: %#", myDictionary);
But you should review your code and provide a more brief explanation that what do you want to achieve and how are you taking an approach for this.
regards,
Arslan

Increment count of duplicate NSDictionary objects in an NSArray?

I am writing a shopping cart application where I have Item Information sent back from server as a NSDictionary object with item number,description,price as values for their keys. I add all these Dictionary objects to mutable array and display in a table view. To manually increment quantity of each item I have added Quantity key to Item Dictionary object.
NSMutableDictionary* itemDictionary = [[NSMutableDictionary alloc] initWithDictionary:inventory.itemDict];
[itemDictionary setObject:[NSString stringWithFormat:#"1"] forKey:#"Quantity"];
[itemsArray addObject:itemDictionary];
[itemDictionary release];
[self.tableView reloadData];
How to increment value for key Quantity if there is a duplicate entry of the same item ? If I add same item to array I would end up with a duplicate, How to find duplicate item i.e., item that has same price, description and item number while ignoring value of Quantity key of the dictionary when searching for duplicates
I would create a new dict containing two items: the inventory dict and the quantity. I'd add an item to itemsArray like this (untested, so beware of typos):
BOOL found = NO;
for (NSDictionary *dict in itemsArray)
{
if ([[dict objectForKey: #"inventorydict"] isEqual: inventory.itemDict])
{
[dict setObject: [NSNumber numberWithInt:
[[dict objectForKey: #"quantity"] intValue] + 1]
forKey: #"quantity"];
found = YES;
break;
}
}
if (!found)
{
[itemsArray addObject:
[NSMutableDictionary dictionaryWithObjectsAndKeys:
inventory.itemDict, #"inventorydict",
[NSNumber numberWithInt: 1], #"quantity",
nil]];
}
So itemsArray contains NSDictionaries with two keys: "inventorydict" and "quantity". "inventorydict" is the dict passed to you containing the item the user bought, and "quantity" is an NSNumber. When you receive a new product item in the basket, you first check if the item is already in the array. If so, you add one to the "quantity" number, otherwise you create a new dictionary with the inventory item and a quantity of 1.
Store your dictionaries in an NSCountedSet. You can then get the quantity via -countForObject:. Use an array only for presentation purposes, so you can sort the values in a sane way. Rebuild this array whenever the set changes, something like so:
- (void)itemsDidChange
{
NSCountedSet *itemSet = [self itemSet];
NSMutableArray *sortedItems = [[NSMutableArray alloc] init];
for (NSDictionary *item in itemSet) {
NSUInteger count = [itemSet countForObject:item];
NSNumber *countNum = [[NSNumber alloc] initWithUnsignedInteger:count];
NSMutableDictionary *arrayItem = [item mutableCopy];
[arrayItem setObject:countNum forKey:KEY_QUANTITY];
[countNum release];
[sortedItems addObject:arrayItem];
[arrayItem release];
}
[sortedItems sortUsingComparator:/* your comparator here */];
[self setRowItems:sortedItems];
[[self tableView] reloadData];
}
Even simpler, use the object directly in your array without changing it at all. When you present the quantity to the user in the UI, just query the itemSet for the count, and use that. The array is then used solely to impose an order on the set's items.
FYI for setObject: you do not need to use stringWithFormat: if you do not have an object to add to it, you can simply use setObject:#"1".
If you want to increment the Quantity, you should be using setObject:[NSNumber numberWithInt:1] instead.
based on Rudy's post made it working this way:
-(void)addToCart:(id)sender
{
appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
BOOL found = NO;
NSString *itemName = // get your item name here
[theDict setObject:itemName forKey:#"name"];
if ([appDelegate.theCartArray isEqual:nil])
{
[appDelegate.theCartArray addObject:theDict];
}
else //implementing Rudy's idea
{
for (theDict in appDelegate.theCartArray)
{
if ([[theDict objectForKey:#"name"] isEqual:itemName])
{
[theDict setObject: [NSNumber numberWithInt:
[[theDict objectForKey: #"quantity"] intValue] + 1]
forKey: #"quantity"];
found = YES;
break;
}
}
if (!found)
{
[appDelegate.theCartArray addObject:
[NSMutableDictionary dictionaryWithObjectsAndKeys:
itemName, #"name",
[NSNumber numberWithInt: 1], #"quantity",
nil]];
}
}
}

Grab all values in NSDictionary inside an NSArray

I have an NSArray full of NSDictionary objects, and each NSDictionary has a unique ID inside. I want to do lookups of particular dictionaries based on the ID, and get all the information for that dictionary in my own dictionary.
myArray contains:
[index 0] myDictionary object
name = apple,
weight = 1 pound,
number = 294,
[index 1] myDictionary object
name = pear,
weight = .5 pound,
number = 149,
[index 3] myDictionary object (etc...)
I want to get the name and weight for the second dictionary object (I won't know the index of the object... if there were only two dicts, I could just make a dictionary from [myArray objectAtIndex:1])
So, say I know the number 149. How would I be able to get the second myDictionary object out of myArray into a new NSDictionary?
As an alternative to Jacob's answer, you could also just ask the dictionary to find the object:
NSPredicate *finder = [NSPredicate predicateWithFormat:#"number = 149"];
NSDictionary *targetDictionary = [[array filteredArrayUsingPredicate:finder] lastObject];
You'd need to iterate through every NSDictionary object in your NSArray:
- (NSDictionary *) findDictByNumber:(NSInteger) num {
for(NSDictionary *dict in myArray) {
if([[dict objectForKey:#"number"] intValue] == num)
return [NSDictionary dictionaryWithObjectsAndKeys:[dict objectForKey:#"weight"], #"weight", [dict objectForKey:#"name"], #"name", nil];
}
return nil;
}

Problem with fetching dictionary objects in array from plist

What is the datatype you use to fetch items whose type is dictionary in plist i.e. nsmutabledictionary or nsdictionary? Because I'm using following code to retrieve dictionary objects from an array of dictionaries in plist.
NSMutableDictionary *_myDict = [contentArray objectAtIndex:0]; //APP CRASHES HERE
NSLog(#"MYDICT : %#",_myDict);
NSString *myKey = (NSString *)[_myDict valueForKey:#"Contents"] ;
[[cell lblFeed] setText:[NSString stringWithFormat:#"%#",myKey]];
Here, on first line it's showing me objc_msgsend. ContentArray is an nsarray and it's contents are showing 2 objects that are there in plist. In plist they are dictionary objects. Then why this error?
Edit
Basically, the contents of my contentArray in console are as shown below :
CONTENT ARRAY :
(
{
favourites = 0;
id = 0;
story = "This is my first record";
timestamp = 324567;
},
{
favourites = 0;
id = 1;
story = "This is my second record";
timestamp = 321456;
}
)
I want to retrieve these dictionary objects from content array.
NSDictionary. You can't simply say
NSMutableDictionary *_myDict = [contentArray objectAtIndex:0];
and hope, that it's a mutable dictionary now. It's still a normal immutable distionary. So, you should write something like:
NSMutableDictionary *_myDict = [NSMutableDictionary dictionaryWithDictionary:[contentArray objectAtIndex:0]];
That'll create mutable dictionary from one that is in the plist.
You can read about it in the "Property List Programming Guide", http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/PropertyLists/index.html
Update:
Also you have a strange plist contents. Available xml-plist types are mentioned here:
http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/PropertyLists/AboutPropertyLists/AboutPropertyLists.html#//apple_ref/doc/uid/10000048i-CH3-SW1
And overall xml-plist structure is described here:
http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/PropertyLists/UnderstandXMLPlist/UnderstandXMLPlist.html#//apple_ref/doc/uid/10000048i-CH6-SW1
Working piece of code
void test() {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *arrayIWillWrite = [NSMutableArray array];
NSMutableDictionary *dictionary;
dictionary = [NSMutableDictionary dictionary];
[dictionary setObject:[NSNumber numberWithInt:0] forKey:#"favourites"];
[dictionary setObject:[NSNumber numberWithInt:0] forKey:#"id"];
[dictionary setObject:#"This is my first record" forKey:#"story"];
[dictionary setObject:[NSNumber numberWithInt:324567] forKey:#"timestamp"];
[arrayIWillWrite addObject:dictionary];
dictionary = [NSMutableDictionary dictionary];
[dictionary setObject:[NSNumber numberWithInt:0] forKey:#"favourites"];
[dictionary setObject:[NSNumber numberWithInt:1] forKey:#"id"];
[dictionary setObject:#"This is my second record" forKey:#"story"];
[dictionary setObject:[NSNumber numberWithInt:321456] forKey:#"timestamp"];
[arrayIWillWrite addObject:dictionary];
[arrayIWillWrite writeToFile:#"/Users/alex/test.plist" atomically:NO];
NSArray *arrayThatWasRead = [NSArray arrayWithContentsOfFile:#"/Users/alex/test.plist"];
NSLog(#"%#", arrayThatWasRead);
NSDictionary *dictionaryFromArrayThatWasRead = [arrayThatWasRead objectAtIndex:0];
NSLog(#"%#", dictionaryFromArrayThatWasRead);
[pool release];
}