I'm trying to figure out how to combine the data from an NSMutable array to be part of an email body. The following code produces the following NSLog output:
- (void)emailBody
{
NSLog(#"Number of Songs: %#", profile.profileNumberOfSongs);
NSLog(#"Profile Length: %#", [self convertSecondstoMMSS:[profile.profileDuration intValue]]);
for (ProfileItems *item in profileItemsNSMArray)
{
NSLog(#"%# %# - %# %#", item.profileItemsSongOrder, item.profileItemsMovementName, item.profileItemsArtist, item.profileItemsSong);
}
}
NSLog output:
Number of Songs: 9
Profile Length: 40:07
1 Seated Flat - Foo Fighters Home
2 Seated Flat - Foo Fighters What If I Do?
3 Standing Climb - Foo Fighters Tired Of You
What is the best way to store this data into a single NSString to be passed to be the body of an email?
Thanks in advance
-Paul
- (NSString *)emailBody
{
NSMutableString *emailBodyString = [NSMutableString string];
[emailBodyString appendFormat:#"Number of Songs: %#", profile.profileNumberOfSongs];
[emailBodyString appendFormat:#"Profile Length: %#", [self convertSecondstoMMSS:[profile.profileDuration intValue]]];
for (ProfileItems *item in profileItemsNSMArray)
{
[emailBodyString appendFormat:#"%# %# - %# %#", item.profileItemsSongOrder, item.profileItemsMovementName, item.profileItemsArtist, item.profileItemsSong];
}
return emailBodyString;
}
Related
I have a piece of code wherein I take an array retrieved from a table and assign it to another string array. However the string array returns back null.
Here is the code:
NSArray *CalorieSet = [ActiveCaloriesDatabase database].ArrayofActivities;
for (ActiveCalories *info in CalorieSet) {
NSLog(#"in app delegate");
NSLog(#"%d: %#, %#", info.uniqueId, info.activity, info.calories);
[_pickData addObject:info.activity];
NSLog(#"array in the for loop %#", CalorieSet);
}
NSLog(#"count here is %d", _pickData.count);
Here's a bit of a newbie question.
I have a NSMutableDictionary *dict
which in the log looks like this:
"test1" = "5";
"test2" = "78";
"test3" = "343";
"test4" = "3";
I need to print each number by itself, but I'm pretty poor at arrays and FOR-sentences.
I was thinking something like:
for (dict) {
double number = [[[dict allKeys] objectAtIndex:0] doubleValue];
NSLog(#"Number: %f",number);
}
Which I want to look like this in the log on each line:
Number: 5
Number: 78
Number: 343
Number: 3
But obviously my "FOR"-method is gibberish.
Any help would be appreciated.
You use a fast enumeration for to do this. It iterates over all the keys in the dictionary:
for (NSString *key in dict) {
double number = [[dict objectForKey:key] doubleValue];
NSLog(#"Number: %f", number);
}
Using blocks:
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"5", #"test1",
#"78", #"test2",
#"343", #"test3",
#"3", #"test4",
nil];
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(#"Number: %#", obj);
}];
NSLog output:
Number: 5
Number: 3
Number: 343
Number: 78
If you just want to log these numbers, try the following:
for (NSString *number in dict) {
NSLog(#"Number: %#",[dict objectForKey:number]);
}
The first answer has two objects being created with the name "number". Instead do:
for (NSString *key in dict) {
NSLog(#"Number as double: %f", [[dict objectForKey:key] doubleValue]);
NSLog(#"Number as string: %#", [dict objectForKey:key]);
}
What's great about fast enumeration is that it creates the object for you (and auto-release them). The key is what's being given to you when fast-enumerating through NSDictionaries. Because you now have the key, you just grab the objectAtKey. In your case, it's a string in your dictionary, so you'll have to either convert it to a double (or whatever type you need), or output as a string. I added examples for both cases above. Good luck!
As already mentioned fast-enumeration is preferable in these cases, but you could also do something like this:
for (int i =0; i<[dict count]; i++){
NSString *str=[dict objectForKey:[NSString stringWithFormat:#"test%d",i+1]];
NSLog(#"%#",str);
}
Okay so I have been working through an example that closely matches what I am trying to achive, the sole difference being that in the example he is directly calling from his database the data he needs to be sectioned etc. Where as I already have a sorted NSArray.
This is the tutorial I am working off - iPhone Development: Creating Native Contacts like screen
I have created a Method that is capturing each entry in the NSArray and putting these results into a alpha based NSDictionary (so their will be a NSDictionary for A,B,C... etc)
here is my method.
//method to sort array and split for use with uitableview Index
- (IBAction)startSortingTheArray:(NSMutableArray *)arrayData
{
//Sort incoming array alphabetically
//sortedArray = [arrayData sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
[self setSortedArray:[arrayData sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)]];
arrayOfCharacters = [[NSMutableArray alloc]init];
objectsForCharacters = [[NSMutableDictionary alloc]init];
for(char c='A';c<='Z';c++)
{
if([sortedArray count] >0)
{
[arrayOfCharacters addObject:[NSString stringWithFormat:#"%c",c]];
[objectsForCharacters setObject:sortedArray forKey:[NSString stringWithFormat:#"%c",c]];
NSLog(#"%#", objectsForCharacters);
}
[sortedArray release];
//Reloads data in table
[self.tableView reloadData];
}
}
This is putting every value into every alpha section, I am hoping someone can help me with making it so that only alpha sections are established if there is a value in the array for it.. then only loading those values into each section, not every section.
This piece of code will do just that and will be much more efficient than filtering the array once for each letter.
//Sort incoming array alphabetically so that each sub-array will also be sorted.
NSArray *sortedArray = [arrayData sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
// Dictionary will hold our sub-arrays
NSMutableDictionary *arraysByLetter = [NSMutableDictionary dictionary];
// Iterate over all the values in our sorted array
for (NSString *value in sortedArray) {
// Get the first letter and its associated array from the dictionary.
// If the dictionary does not exist create one and associate it with the letter.
NSString *firstLetter = [value substringWithRange:NSMakeRange(0, 1)];
NSMutableArray *arrayForLetter = [arraysByLetter objectForKey:firstLetter];
if (arrayForLetter == nil) {
arrayForLetter = [NSMutableArray array];
[arraysByLetter setObject:arrayForLetter forKey:firstLetter];
}
// Add the value to the array for this letter
[arrayForLetter addObject:value];
}
// arraysByLetter will contain the result you expect
NSLog(#"Dictionary: %#", arraysByLetter);
Note that arraysByLetter is a dictionary that contains one array per "first letter" that exists in your initial data.
--- Added on 2011-09-23 ---
[sortedArray removeAllObjects];
NSArray *sortedKeys = [arraysByLetter.allKeys sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
for (NSString *key in sortedKeys) {
[sortedArray addObject:key];
[sortedArray addObjectsFromArray: [arraysByLetter objectForKey:key]];
}
NSLog(#"Sorted Array: %#", sortedArray);
The output is the following:
C,
Computer,
H,
Helene,
Hello,
J,
Jules,
W,
World
Looks like you need to filter sortedArray with a predicate for each letter. Something like this...
for(char c='A';c<='Z';c++) {
NSPredicate *predicate =
[NSPredicate predicateWithFormat:#"SELF beginswith[c] '%c'", c];
NSArray *objectsBeginningWithCurrentLetter = [array filteredArrayUsingPredicate:predicate];
if([sortedArray count] >0)
{
[arrayOfCharacters addObject:[NSString stringWithFormat:#"%c",c]];
if ([objectsBeginningWithCurrentLetter count] > 0) {
[objectsForCharacters setObject:objectsBeginningWithCurrentLetter forKey:[NSString stringWithFormat:#"%c",c]];
NSLog(#"%#", objectsForCharacters);
}
}
[sortedArray release];
//Reloads data in table
[self.tableView reloadData];
}
I have got a NSMutableArray that is structured as follow:
{
{
AccountNumber:Test1
Type: Electricity
}
{
AccountNumber:Test2
Type: Water
}
{
AccountNumber:Test3
Type: Water
}
}
How to print out the account number that are in Water type?
What I have tried is as follow:
- (NSUInteger)indexOfObjectIdenticalTo:(id)data{ return data; }
But I didn't understand how to do it.
Check out NSPredicate. It will allow to you essentially define a query and apply it to your array to filter the results. This is much faster than a iterative loop through the array to find what you are looking for. For your example, you would simply need to do the following:
NSString *type = #"Water";
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"Type == %#", type];
NSArray *results = [myArray filteredArrayUsingPredicate:predicate];
Assuming each item in the array is a NSDictionary, and all the keys/values are NSStrings, you could do something like this:
for (NSDictionary *dict in myArray) {
if ([[dict objectForKey:#"Type"] isEqualToString:#"Water"]) {
NSLog(#"Account number %#", [dict objectForKey:#"AccountNumber"]);
}
}
I'm using MGTWitterEngine and I cannot figure out why my dictionary items are returning null.
I have this method:
- (void)searchResultsReceived:(NSArray *)searchResults forRequest:(NSString *)connectionIdentifier{
NSDictionary *result = [searchResults objectAtIndex:0];
NSString *fromUser = [result valueForKey:#"from_user"];
NSLog(#"from user: %#", fromUser);
}
And for some reason, my NSLog always displays "from user: NULL". I can do an NSLog of searchResults which dumps the contents of the search correctly, but I can't figure out how to parse the information. Any help would be greatly appreciated.
Look at this question: Parsing Search Result with MGTwitterEngine in Objective C
They use:
- (void)searchResultsReceived:(NSArray *)searchResults
forRequest:(NSString *)connectionIdentifier
{
if ([searchResults count] > 0)
{
NSDictionary *result = [searchResults objectAtIndex:0];
NSString *fromUser = [result valueForKey:#"from_user"];
NSString *fromUserID = [result valueForKey#"from_user_id"];
// ...
NSString *text = [result valueForKey#"text"];
NSLog(#"User %#(%#): %#", fromUser, fromUserID, text);
}
}
It is similar to your code with a check on searchResults count.