Retrieve 1 specific key from several NSArrays and add them together - ios

In my app, I am needing to loop through each NSArray, get the NSInteger associated with the key 'people' in the NSArray, and then add them all together. What would be a good starting point for first retrieving each specific NSInteger from each NSArray?
The array in question returns like this in console.
(
"<Prayers:DDomBXIONY:(null)> {\n Anonymous = 1;\n DeviceID = 123;\n FirstName = Name;\n LastName = Name;\n Location = HI;\n PrayerWarriors = 8;\n Request = Hi;\n Title = Hi;\n UserId = RtXN6QZsgaIiPw4SjFWGtkxXx;\n dateMade = \"Jan_09_2015\";\n}"
)
Basically just need to retrieve NSInteger from each PrayerWarriors key, and add them all together.
(
"<Prayers:DDomBXIONY:(null)> {\n Anonymous = 1;\n DeviceID = 123;\n FirstName = Name;\n LastName = Name;\n Location = HI;\n PrayerWarriors = 8;\n Request = Hi;\n Title = Hi;\n UserId = RtXN6QZsgaIiPw4SjFWGtkxXx;\n dateMade = \"Jan_09_2015\";\n}",
"<Prayers:yG7GC4bCIH:(null)> {\n Anonymous = 1;\n DeviceID = 123;\n FirstName = Name;\n LastName = Name;\n Location = bye;\n PrayerWarriors = 0;\n Request = bye;\n Title = bye;\n UserId = RtXN6QZsgaIiPw4SjFWGtkxXx;\n dateMade = \"Jan_09_2015\";\n}"
)

So without understanding exactly how your PFObject works, I'm going to assume it's like a dictionary.
Add each of your objects to a single array:
NSMutableArray *arrayHoldingPrayersObjects = [NSMutableArray alloc] init];
arrayHoldingPrayersObjects[0] = prayerObject1;
arrayHoldingPrayersObjects[1] = prayerObject2;
arrayHoldingPrayersObjects[2] = prayerObject3;
etc...
Then create a integer variable outside of a for loop and iterate through your objects, adding the value for PrayerWarrior at each iteration.
int totalPrayerWarriors = 0;
for (int i = 0; i < arrayHoldingPrayersObjects.count; i++)
{
NSMutableDictionary *prayerObject = arrayHoldingPrayersObjects[i];
totalPrayerWarriors += [prayerObject objectForKey:#"PrayerWarriors"] intValue];
}
You should end up with a correct total from all arrays. Do some tests to make sure it's accurate for you. Hope this helps.
*EDIT
The error you're getting indicates that it actually is a NSMutableArray, which you can't access using methods like objectForKey, so... there must be a method provided by PFObject that allows you to do that. OR, if PrayerWarriors is reliably the [5]th value (including 0) in the array, then you might be able to access it by index.
replace the lines:
NSMutableDictionary *prayerObject = arrayHoldingPrayersObjects[i];
totalPrayerWarriors += [prayerObject objectForKey:#"PrayerWarriors"] intValue];
with
NSMutableArray *prayerObject = arrayHoldingPrayersObjects[i];
totalPrayerWarriors += prayerObject[5];

Not sure where the mutable array is coming from. Parse.com will always produce immutable arrays as far as I know. So lets say you've retrieved Prayers with:
PFQuery *query = [PFQuery queryWithClassName:#"Prayers"];
[query findObjectsInBackgroundWithBlock:^(NSArray *prayers, NSError *error) {
// see how it's an NSArray, not mutable
}];
Now you want the total of the retrieved PrayerWarrior attributes, so...
[query findObjectsInBackgroundWithBlock:^(NSArray *prayers, NSError *error) {
NSInteger total = 0;
for (PFObject *p in prayers) {
NSNumber *warriorCount = p[#"PrayerWarriors"];
total += [warriorCount intValue]; // notice we cannot add nsnumbers directly (we need intValue)
}
NSLog(#"total warriors = %d", total);
}];

Related

Firebase sort query gives (unsorted) dictionary results

So I'm sure I'm missing something here, but when I wish to do a query for, say, the top 10 scores in a certain game, Firebase returns the top 10 scores, however since they are then gives back as a dictionary (key generated with childByAutoId), they are 'unsorted' when received on the client side (so to display a top 10 you have to sort them again)...
FIRDatabaseReference *ref = [[FIRDatabase database] reference];
FIRDatabaseQuery *jungleHighscoresQuery = [[[ref child:#"jungleScores"] queryOrderedByChild:#"score"] queryLimitedToLast:4];
[jungleHighscoresQuery observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot){
NSDictionary *postDict = snapshot.value;
NSLog(#"%#", postDict);
}];
The above code gives the following output (these are the top 4 scores among the ~20 in the database):
{
"-KIUhe_9TLQoy_zNbJT0" = {
score = 290;
userid = oMqoPGJYsGWHffYx8N6vDk3Osh72;
};
"-KIUj8VUyNMgyZ135dI_" = {
score = 560;
userid = oMqoPGJYsGWHffYx8N6vDk3Osh72;
};
"-KIUjK15Gy9PRB_JBWOA" = {
score = 240;
userid = oMqoPGJYsGWHffYx8N6vDk3Osh72;
};
"-KIUlZ1a03r7bjPYNueG" = {
score = 740;
userid = oMqoPGJYsGWHffYx8N6vDk3Osh72;
};
}
I know it's an easy task to just sort it all again, but it seems weird to have to do.
There was an easy solution after all, just had to grab the enumerator instead of the dictionary:
NSEnumerator *enumerator = snapshot.children;
and then just iterate through them with [enumerator nextObject]

How to put NSDictionary inside NSDictionary into UITableView?

I receive following NSDictionary from my server. I don't know how to access each row and put them in UITableView. I need a for loop or something to access each of them one by one: I get following when I say:
NSLog(#"%#",dict);
{
chores = (
{
"first_due_date" = "2016-03-12";
frequency = weekly;
id = 1;
name = TEST;
parent = Blah;
"previous_chores" = (
);
},
{
"first_due_date" = "2016-03-12";
frequency = weekly;
id = 2;
name = TEST2;
parent = Blah;
"previous_chores" = (
);
},
{
"first_due_date" = "2016-03-12";
frequency = weekly;
id = 3;
name = TEST3;
parent = Blah;
"previous_chores" = (
);
}
);
}
I guess you can directly use the array without split it like following:
Suppose you have an array with dictionary and inside the dictionary as your data and kiran said:
NSArray *arrChores = [dict valueForKey #"Chores"];
Your array look like 0th index is:
{
"first_due_date" = "2016-03-12";
frequency = weekly;
id = 1;
name = TEST;
parent = Blah;
"previous_chores" = (
);
}
so you can print the name like following in cellForrowIndex:
NSLog(#"=== %#",[[arrChores objectAtIndex:indexPath.row]valueForKey:#"name"])
More easy and less maintain :)
Create a model for Chores.
Looking at the dictionary.
Chores is an array consisting of dictionaries in it.
So you can have array like this
arrChoresGlobal = [NSMutableArray new];
NSArray *arrChores = [dict valueForKey #"Chores"];
Then iterate this array and have a model.
like below
for(NSDictionary *dctChore in arrChores)
{
SomeModel *obj = [SomeModel new];
obj.first_due_date = [dctChore valueForKey:#"first_due_date"];
[arrChoresGlobal addObject:obj];
}
Then use this array count in numberOfRows in tableview
return [arrChoresGlobal count];
and in cellForRowAtIndexPath
SomeModel *obj = [arrChoresGlobal objectAtIndex:indexPath.row];
Edit :- Longer but systematic way :)

Access email in EKParticipant/EKAttendee

I want to get the email address of the attendee of an event in the EKEventKit.
I have the following code:
if ( event.attendees.count > 0)
{
NSArray *people = event.attendees;
for(EKParticipant *person in people)
{
if ( person.participantType == EKParticipantTypePerson && person.URL.resourceSpecifier.length > 0)
{
NSString *dataString = [NSString stringWithFormat:#"event_id=%ld&name=%#&is_me=%d&email=%#&role=%#",event_id,person.name, person.isCurrentUser,person.URL.resourceSpecifier, #"attendee"];
//<DO SOMETHING USEFUL WITH dataString>;
}
}
}
When I run the code person populates with the following data:
EKAttendee <0x17809acc0> {UUID = 4F657EA4-452A-412B-A9AA-FEC5551DC096; name = A. Real Person; email = realperson#therightdomain.com; status = 0; role = 0; type = 1}
How to I access the email field?
I tried (as above) to use URL.resourceSpecifier, but that frequently is some strange string that is definitely NOT an email address.
The "Description" of the EKParticipant object is a property list of sorts. I tried several different methods of parsing that list into something containing key:value pairs unsuccessfully. So I wrote the following:
// This is re-useable code that converts any class description field into a dictionary that can be parsed for info
NSMutableDictionary *descriptionData = [NSMutableDictionary dictionary];
for (NSString *pairString in [person.description componentsSeparatedByString:#";"])
{
NSArray *pair = [pairString componentsSeparatedByString:#"="];
if ( [pair count] != 2)
continue;
[descriptionData setObject:[[pair objectAtIndex:1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:[[pair objectAtIndex:0]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}
With this I simply get the email address with
[descriptionData valueForKey:#"email"]
I tried to answer this same question in "how to get ekevent EKparticipant email?" thread:
What you need to do is use EKPrincipal:ABRecordWithAddressBook and then extract email from there. Like this:
NSString *email = nil;
ABAddressBookRef book = ABAddressBookCreateWithOptions(nil, nil);
ABRecordRef record = [self.appleParticipant ABRecordWithAddressBook:book];
if (record) {
ABMultiValueRef value = ABRecordCopyValue(record, kABPersonEmailProperty);
if (value
&& ABMultiValueGetCount(value) > 0) {
email = (__bridge id)ABMultiValueCopyValueAtIndex(value, 0);
}
}
Note that calling ABAddressBookCreateWithOptions is expensive so you might want to do that only once per session.
If you can't access the record, then fall back on URL.resourceSpecifier.
In Swift 4:
private static func getParticipantDescriptionData(_ participant: EKParticipant) -> [String:String] {
var descriptionData = [String: String]()
for pairString in participant.description.components(separatedBy: ";") {
let pair = pairString.components(separatedBy: "=")
if pair.count != 2 {
continue
}
descriptionData[pair[0].trimmingCharacters(in: .whitespacesAndNewlines)] =
pair[1].trimmingCharacters(in: .whitespacesAndNewlines)
}
return descriptionData
}

How to retrieve the pretext before an array in iOS Objective C (parse)

Array object at index 0---:
<Merchandise:AW9JgReRyQ:(null)>
{
ACL = "<PFACL: 0x201b2590>\";
CoverPhotos = "<ItemPhotos:L5ln3ZN5rm>\";
item = ugh;
listingprice = 356;
originalprice = "25)";
user = "<PFUser:KdRfesAJA3>";
},
I have implemented my iOS app using Parse.com
In that I have an array of objects (Array of dictionaries)
in those I have print the 1st object of that array..
I have some pre text Merchandise:AW9JgReRyQ:(null before every object / dictionary which is related to object id
i want to get the preText " Merchandise:AW9JgReRyQ:(null) " or atleast "AW9JgReRyQ"
How to do ..>?
Total entire array of all objects is
array-------
(
"<Merchandise:AW9JgReRyQ:(null)>
{\n ACL = \"<PFACL: 0x201b2590>\";\n CoverPhotos = \"<ItemPhotos:L5ln3ZN5rm>\";\n Photos = \"<PFRelation: 0x201bff80>(<00000000>.(null) -> ItemPhotos)\";\n brand = \"Baby Gap\";\n description = \"\\nFight\";\n item = ugh;\n listingprice = 356;\n originalprice = \"25)\";\n user = \"<PFUser:KdRfesAJA3>\";\n}",
"<Merchandise:bMPFijErWI:(null)>
{\n ACL = \"<PFACL: 0x201a2300>\";\n CoverPhotos = \"<ItemPhotos:4pm7vX7q26>\";\n Photos = \"<PFRelation: 0x2019a490>(<00000000>.(null) -> ItemPhotos)\";\n brand = \"3 Pommes\";\n description = Sett;\n item = udder;\n listingprice = 245;\n originalprice = 245;\n user = \"<PFUser:KdRfesAJA3>\";\n}"
)
It seems like you have two options for this. Either parse each one out into a string (definitely the less elegant/way uglier way). Or also it looks more likely that it could be an array of arrays that contain a string and dictionary.
If it ends up being the second option, you could easily just grab the object at index 0 twice to get the preText your looking for. However, if thats no avail..then you can just go for it like so:
//Convert your object into an NSString
NSString *converted = (NSString*)[yourArray objectAtIndex:i];
//Or..your may need to do NSString *converted = [NSString stringWithFormat:#"%#",[yourArray objectAtIndex:0]];
NSArray *firstSplitterArray = [converted componentsSeparatedByString:#"<"];//split by <
NSString *partialSplit = [splitterArray objectAtIndex:0];
NSArray *secondSplitterArray = [partialSplit componentsSeparatedByString:#">"];//split by >
NSString *yourPreText = [secondSplitterArray objectAtIndex:0];//final step
//now yourPreText should equal Merchandise:AW9JgReRyQ:(null)
I wrote this according to your first code snippet. If there is actually a leading quotation mark or something, you'll need to change your indexes. But this gives you the idea. Just do some print statements to verify your arrays at each step and you will be good to go. Not the cleanest, but if your in a pinch this could work.

How to Serialize a NSCFArray (possible JSON) to NSDictionary?

I'm really stuck right now while using BZForursquare to get nearby Venues into a UITableView.
BZFoursquare: https://github.com/baztokyo/foursquare-ios-api
I get my Requestresult inside the requestDidFinishLoading Delegate Method. In this Method the request Object contains several NSDictionaries and one Dictionary is in request.response. This response Dictionary contains one entry with key="venues" and as Value a JSON Object. When I put this value Object into a dictionary the type seems not to be a Dictionary but a NSCFArray:
#pragma mark BZFoursquareRequestDelegate
- (void)requestDidFinishLoading:(BZFoursquareRequest *)request {
self.meta = request.meta;
self.notifications = request.notifications;
self.response = [request.response objectForKey:#"venues"];
self.request = nil;
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"%#",[self.response objectForKey:#"name"]);
}
I assume this because the NSLog Line gives me the following error:
-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x1e5c90f0
Now I'm totaly confused and tried some failed attempts to get this JSON from whatever kind od Datatype it is into a NSDictionary. One attempt was to put the value Object into an NSString and use
[NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];
to get it into a Dictionary but that also failed because it still remains a NSCFArray. Can someone please tell me how I get content of
[request.response objectForKey:#"venues"]
into a NSDictionary so that I can populate my UITabelview with this content?
EDIT:
Here is whats in the value part from the Dictionary request.response:
(
{
categories = (
{
icon = {
name = ".png";
prefix = "https://foursquare.com/img/categories/food/default_";
sizes = (
32,
44,
64,
88,
256
);
};
id = 4bf58dd8d48988d10b941735;
name = "Falafel Restaurant";
pluralName = "Falafel Restaurants";
primary = 1;
shortName = Falafel;
}
);
contact = {
};
hereNow = {
count = 0;
groups = (
);
};
id = 4df3489dfa76abc3d86c4585;
likes = {
count = 0;
groups = (
);
};
location = {
cc = DE;
city = "Vinn";
country = Germany;
distance = 92;
lat = "51.44985";
lng = "16.648693";
state = "Nordrhein-Westfalen";
};
name = "Yildiz D\U00f6ner";
specials = (
);
stats = {
checkinsCount = 3;
tipCount = 0;
usersCount = 2;
};
verified = 0;
}
And this seems to be from Type of NSCFArray. And how can I create from this another Dictionary so that I can access the JSON Values by key? Sorry if I'm really slow today...
You ask for "venues" which I assume is an array of such. So after deserializing the json, log the return object to see what you get. It's almost for sure an array of dictionaries.

Resources