Remove " " from key string in a NSMutableDictionary - ios

Here's my dictionary:
Birthdate = "01-01-0001";
CareerField = 3;
Gender = 2;
"Interests[0].UserProfileId" = 19594;
"Interests[0].UserSurveyId" = 1;
SocialStatus = 2;
Studies = 3;
But I want the Interests key to be without "".Like that:
Birthdate = "01-01-0001";
CareerField = 3;
Gender = 2;
Interests[0].UserProfileId = 19594;
Interests[0].UserSurveyId = 1;
SocialStatus = 2;
Studies = 3;
UPDATE:
Interests i must send them like array.
[dict setObject:self.birthdayDate forKey:#"Birthdate"]
[dict setObject:#(self.occupationPickerRow + 1) forKey:#"CareerField"];
for (int i = 0; i < [interestsArray count]; i++) {
NSString *stringSurveyId = [NSString stringWithFormat:#"%#%d%#", #"Interests[", indexCount, #"].UserSurveyId"];
NSString *stringUserProfileId = [NSString stringWithFormat:#"%#%d%#", #"Interests[", indexCount, #"].UserProfileId"];
[dict setObject:[interestsArray objectAtIndex:i] forKey:stringSurveyId];
[dict setObject:#([[[MZEngine sharedInstance] currentUserModel] userId]) forKey:stringUserProfileId];
indexCount++;
}

Related

NSDictionary Getting Repeated values

I know this may be a repeated question but I googled a lot but not able to find a suitable answer for me.
I have a NSMutableArray which has two NSDictionary with Keys and values which I need to populated on a UITableView. I have retrieved the value of the dictionary which I'm going populate using
NSMutableArray *mutArray = [responseArray valueForKey:#"Table"];
And I did like
NSMutableSet *names = [NSMutableSet set];
NSMutableArray *mutArray1 = [[NSMutableArray alloc] init];
for (id obj in mutArray) {
NSString *destinationName = [obj valueForKey:#"AssetClassName"];
if (![names containsObject:destinationName]) {
[mutArray1 addObject:destinationName];
[names addObject:destinationName];
}
}
Because the value AssetClassName is repeated. Now I have three values in mutArray1 which I need to show as UITableView section. Under AssetClassName I have Some data which determines the row in that section.
For retrieving that data I'm doing like
for (int i = 0; i < [mutArray1 count]; i++) {
NSMutableDictionary *a = [[NSMutableDictionary alloc] init];
NSMutableDictionary *b = [[NSMutableDictionary alloc] init];
for (NSDictionary *dict in mutArray) {
if ([[mutArray1 objectAtIndex:i] isEqualToString:[dict valueForKey:#"AssetClassName"]]) {
[a setObject:[dict objectForKey: #"SubAssetClassName"] forKey:#"Investment Categories"];
[a setObject:[dict valueForKey:#"Amount"] forKey:#"Amount (EUR)"];
[a setObject:[dict valueForKey:#"AllocationPercentage"] forKey:#"%"];
[a setObject:[dict valueForKey:#"ModelAllocationPercentage"] forKey:#"ModelAllocationPercentage"];
[b setObject:a forKey:[dict valueForKey:#"SubAssetClassName"]];
[mutdict setObject:b forKey:[dict valueForKey:#"AssetClassName"]];
}
}
}
mutdict is a NSMutableDictionary declared globally and is instantiate in viewdidLoad
mutdict = [[NSMutableDictionary alloc] init];
The values are inserted into mutdict as I needed. Each SubAssetClassName is added into AssetclassName accordingly.
But my problem is in my final dictionary i.e mutdict the values for SubAssetClassName is repeated.
Can anybody tell how to solve this.
My console
"AssetClassName" = {
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "HIGH YIELD BONDS";
"ModelAllocationPercentage" = 22;
};
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "HIGH YIELD BONDS";
"ModelAllocationPercentage" = 22;
};
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "HIGH YIELD BONDS";
"ModelAllocationPercentage" = 22;
};
};
"AssetClassName" = {
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "EMERGING MARKETS EQUITIES";
"ModelAllocationPercentage" = 10;
};
};
"AssetClassName" = {
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "STRUCTURED PRODUCTS";
"ModelAllocationPercentage" = 10;
};
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "STRUCTURED PRODUCTS";
"ModelAllocationPercentage" = 10;
};
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "STRUCTURED PRODUCTS";
"ModelAllocationPercentage" = 10;
};
};
}
Here I can see that all SubAssetClass values are same for each section but actually its not.
How can I solve this.
You need to create a new instance of your mutable dictionary inside the loop. Right now you create one instance and update it over and over. This results in one dictionary being added over and over.
Change you code as follows:
for (NSInteger i = 0; i < [mutArray1 count]; i++) {
NSMutableDictionary *b = [[NSMutableDictionary alloc] init];
for (NSDictionary *dict in mutArray) {
if ([[mutArray1 objectAtIndex:i] isEqualToString:[dict valueForKey:#"AssetClassName"]]) {
NSMutableDictionary *a = [[NSMutableDictionary alloc] init];
[a setObject:[dict objectForKey: #"SubAssetClassName"] forKey:#"Investment Categories"];
[a setObject:[dict valueForKey:#"Amount"] forKey:#"Amount (EUR)"];
[a setObject:[dict valueForKey:#"AllocationPercentage"] forKey:#"%"];
[a setObject:[dict valueForKey:#"ModelAllocationPercentage"] forKey:#"ModelAllocationPercentage"];
[b setObject:a forKey:[dict valueForKey:#"SubAssetClassName"]];
[mutdict setObject:b forKey:[dict valueForKey:#"AssetClassName"]];
}
}
}
Also, in most cases you should not be using valueForKey:. Use objectForKey: unless you have a clear and specific need to use key-value coding instead of simply getting an object from the dictionary for a given key.

Dictionary object can't convert into a JSON object objective-c

hello I have a NSMutableArray like this.
<__NSArrayM 0x137e9f270>(
{
CanLoadMore = 0;
IsFinalLevel = 1;
NextLevelApprovers = (
);
OrgStructure = (
{
CreatedBy = 1;
CreatedDate = "2015-07-29T12:10:34.297";
Deleted = 0;
DeletedBy = 0;
DeletedDate = "1901-01-01T00:00:00";
EntityHeadCode = 17098;
EntityHeadName = "<null>";
IsPermitted = 0;
LegislativeCode = LKA;
LevelId = 1;
NodeId = 1;
OrgEntity = Group;
OrgLevelDescription = "";
OrgLevelName = "ABCD Holdings";
OrgStructureId = 1;
ParentNodeId = 0;
RefOrgLevelId = 1;
Status = 1;
UpdatedBy = 17113;
UpdatedDate = "2016-04-07T08:53:13.727";
},
{
CreatedBy = 17113;
CreatedDate = "2016-04-06T12:17:19.75";
Deleted = 0;
DeletedBy = 0;
DeletedDate = "1901-01-01T00:00:00";
EntityHeadCode = 0;
EntityHeadName = "<null>";
IsPermitted = 0;
LegislativeCode = LKA;
LevelId = 2;
NodeId = 2;
OrgEntity = Company;
OrgLevelDescription = "";
OrgLevelName = "ABCD HCM";
OrgStructureId = 2;
ParentNodeId = 1;
RefOrgLevelId = 6;
Status = 1;
UpdatedBy = 17098;
UpdatedDate = "2016-07-29T11:14:12.513";
}
);
PreviousLevelCount = 0;
RequestDetails = {
AutoId = 20;
LevelId = 1;
ModuleId = 2;
NoOfLevels = 1;
ObjectId = 20;
ObjectName = "Leave Request";
RequestForm = "{\"LeaveEntryCode\":0,\"RequestId\":0,\"EmployeeCode\":17227,\"LeaveYear\":2016,\"LeaveTypeCode\":1,\"LeaveReasonCode\":2,\"BaseType\":\"ess\",\"StartDate\":\"2016-08-02T00:00:00\",\"EndDate\":\"2016-08-02T00:00:00\",\"NoOfDays\":1.0,\"StartDateSession\":\"full\",\"EndDateSession\":\"half\",\"PreApproved\":false,\"ForDate\":\"1901-01-01T00:00:00\",\"Remarks\":\"Test 1\",\"CoveringPersonCode\":0,\"AttachedDocument\":null,\"RequestStatus\":\"P\",\"Deleted\":false,\"Status\":false,\"CreatedBy\":0,\"CreatedDate\":\"0001-01-01T00:00:00\",\"UpdatedBy\":0,\"UpdatedDate\":\"0001-01-01T00:00:00\",\"DeletedBy\":0,\"DeletedDate\":\"0001-01-01T00:00:00\",\"ModuleId\":2,\"ObjectId\":20,\"StartDateString\":\"08/02/2016\",\"EndDateString\":\"08/02/2016\",\"LeaveDayList\":[\"08/02/2016-FH,08/02/2016-SH\"],\"SystemLeaveTypeCode\":\"ANN\",\"LeaveTypeName\":\"ANNUAL\",\"Employee\":null,\"LieuDayList\":null,\"BaseLeaveType\":\"ANN\",\"CoveringPersonName\":,\"LeaveReasonName\":\"Leave TypeCasual - Leave - Leave Reason\",\"DocumentSource\":\"LEAVE\"}";
RequestId = 20;
RequestedDate = "2016-08-02T05:07:07.127";
WorkflowId = 2;
};
RequesterDetails = {
AdminRequesterName = "";
DisplayName = "<null>";
EmployeeCode = 17227;
EmployeeNumber = MM0000019;
EtfNo = "";
Gender = Female;
ImagePath = "/profile/image/759006c5e4214f0";
Name = haniAAAA;
};
}
)
I want to convert this to JSON object. So I did like this.
NSError *jsonError;
NSData *objectData = [[[[dm.mutArraySelectedReq objectAtIndex:index] objectForKey:#"RequestDetails"] valueForKey:#"RequestForm"] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
but my jsondictionary is always nil. What is the error with this RequestForm object.
Please help me.
Thanks
UPDATE
This is the string I want to convert into a json.
{\"LeaveEntryCode\":0,\"RequestId\":0,\"EmployeeCode\":17227,\"LeaveYear\":2016,\"LeaveTypeCode\":1,\"LeaveReasonCode\":2,\"BaseType\":\"ess\",\"StartDate\":\"2016-08-02T00:00:00\",\"EndDate\":\"2016-08-02T00:00:00\",\"NoOfDays\":1.0,\"StartDateSession\":\"full\",\"EndDateSession\":\"half\",\"PreApproved\":false,\"ForDate\":\"1901-01-01T00:00:00\",\"Remarks\":\"Test 1\",\"CoveringPersonCode\":0,\"AttachedDocument\":null,\"RequestStatus\":\"P\",\"Deleted\":false,\"Status\":false,\"CreatedBy\":0,\"CreatedDate\":\"0001-01-01T00:00:00\",\"UpdatedBy\":0,\"UpdatedDate\":\"0001-01-01T00:00:00\",\"DeletedBy\":0,\"DeletedDate\":\"0001-01-01T00:00:00\",\"ModuleId\":2,\"ObjectId\":20,\"StartDateString\":\"08/02/2016\",\"EndDateString\":\"08/02/2016\",\"LeaveDayList\":[\"08/02/2016-FH,08/02/2016-SH\"],\"SystemLeaveTypeCode\":\"ANN\",\"LeaveTypeName\":\"ANNUAL\",\"Employee\":null,\"LieuDayList\":null,\"BaseLeaveType\":\"ANN\",\"CoveringPersonName\":,\"LeaveReasonName\":\"Leave TypeCasual - Leave - Leave Reason\",\"DocumentSource\":\"LEAVE\"}
UPDATE - CORRECT STRING
{\"LeaveEntryCode\":0,\"RequestId\":0,\"EmployeeCode\":17167,\"LeaveYear\":2016,\"LeaveTypeCode\":2,\"LeaveReasonCode\":0,\"BaseType\":\"ess\",\"StartDate\":\"2016-08-01T00:00:00\",\"EndDate\":\"2016-08-01T00:00:00\",\"NoOfDays\":1.0,\"StartDateSession\":\"full\",\"EndDateSession\":\"full\",\"PreApproved\":false,\"ForDate\":\"1901-01-01T00:00:00\",\"Remarks\":\"\",\"CoveringPersonCode\":0,\"AttachedDocument\":null,\"RequestStatus\":\"P\",\"Deleted\":false,\"Status\":false,\"CreatedBy\":0,\"CreatedDate\":\"0001-01-01T00:00:00\",\"UpdatedBy\":0,\"UpdatedDate\":\"0001-01-01T00:00:00\",\"DeletedBy\":0,\"DeletedDate\":\"0001-01-01T00:00:00\",\"ModuleId\":2,\"ObjectId\":20,\"StartDateString\":\"08/01/2016\",\"EndDateString\":\"08/01/2016\",\"LeaveDayList\":[\"08/01/2016-FH,08/01/2016-SH\"],\"SystemLeaveTypeCode\":\"CAS\",\"LeaveTypeName\":\"CASUAL\",\"Employee\":null,\"LieuDayList\":null,\"BaseLeaveType\":\"ANN\",\"CoveringPersonName\":null,\"LeaveReasonName\":\"Leave TypeCasual - Leave - Leave Reason\",\"DocumentSource\":\"LEAVE\"}
WRONG STRING
{\"LeaveEntryCode\":0,\"RequestId\":0,\"EmployeeCode\":17227,\"LeaveYear\":2016,\"LeaveTypeCode\":1,\"LeaveReasonCode\":2,\"BaseType\":\"ess\",\"StartDate\":\"2016-08-02T00:00:00\",\"EndDate\":\"2016-08-02T00:00:00\",\"NoOfDays\":1.0,\"StartDateSession\":\"full\",\"EndDateSession\":\"half\",\"PreApproved\":false,\"ForDate\":\"1901-01-01T00:00:00\",\"Remarks\":\"Test 1\",\"CoveringPersonCode\":0,\"AttachedDocument\":null,\"RequestStatus\":\"P\",\"Deleted\":false,\"Status\":false,\"CreatedBy\":0,\"CreatedDate\":\"0001-01-01T00:00:00\",\"UpdatedBy\":0,\"UpdatedDate\":\"0001-01-01T00:00:00\",\"DeletedBy\":0,\"DeletedDate\":\"0001-01-01T00:00:00\",\"ModuleId\":2,\"ObjectId\":20,\"StartDateString\":\"08/02/2016\",\"EndDateString\":\"08/02/2016\",\"LeaveDayList\":[\"08/02/2016-FH,08/02/2016-SH\"],\"SystemLeaveTypeCode\":\"ANN\",\"LeaveTypeName\":\"ANNUAL\",\"Employee\":null,\"LieuDayList\":null,\"BaseLeaveType\":\"ANN\",\"CoveringPersonName\":,\"LeaveReasonName\":\"Leave TypeCasual - Leave - Leave Reason\",\"DocumentSource\":\"LEAVE\"}
Its working Fine
NSString *str = #"{\"LeaveEntryCode\":0,\"RequestId\":0,\"EmployeeCode\":17167,\"LeaveYear\":2016,\"LeaveTypeCode\":2,\"LeaveReasonCode\":0,\"BaseType\":\"ess\",\"StartDate\":\"2016-08-01T00:00:00\",\"EndDate\":\"2016-08-01T00:00:00\",\"NoOfDays\":1.0,\"StartDateSession\":\"full\",\"EndDateSession\":\"full\",\"PreApproved\":false,\"ForDate\":\"1901-01-01T00:00:00\",\"Remarks\":\"\",\"CoveringPersonCode\":0,\"AttachedDocument\":null,\"RequestStatus\":\"P\",\"Deleted\":false,\"Status\":false,\"CreatedBy\":0,\"CreatedDate\":\"0001-01-01T00:00:00\",\"UpdatedBy\":0,\"UpdatedDate\":\"0001-01-01T00:00:00\",\"DeletedBy\":0,\"DeletedDate\":\"0001-01-01T00:00:00\",\"ModuleId\":2,\"ObjectId\":20,\"StartDateString\":\"08/01/2016\",\"EndDateString\":\"08/01/2016\",\"LeaveDayList\":[\"08/01/2016-FH,08/01/2016-SH\"],\"SystemLeaveTypeCode\":\"CAS\",\"LeaveTypeName\":\"CASUAL\",\"Employee\":null,\"LieuDayList\":null,\"BaseLeaveType\":\"ANN\",\"CoveringPersonName\":null,\"LeaveReasonName\":\"Leave TypeCasual - Leave - Leave Reason\",\"DocumentSource\":\"LEAVE\"}" ;
NSError *jsonError;
NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&jsonError];
**OutPut**
Printing description of json:
{
AttachedDocument = "<null>";
BaseLeaveType = ANN;
BaseType = ess;
CoveringPersonCode = 0;
CoveringPersonName = "<null>";
CreatedBy = 0;
CreatedDate = "0001-01-01T00:00:00";
Deleted = 0;
DeletedBy = 0;
DeletedDate = "0001-01-01T00:00:00";
DocumentSource = LEAVE;
Employee = "<null>";
EmployeeCode = 17167;
EndDate = "2016-08-01T00:00:00";
EndDateSession = full;
EndDateString = "08/01/2016";
ForDate = "1901-01-01T00:00:00";
LeaveDayList = (
"08/01/2016-FH,08/01/2016-SH"
);
LeaveEntryCode = 0;
LeaveReasonCode = 0;
LeaveReasonName = "Leave TypeCasual - Leave - Leave Reason";
LeaveTypeCode = 2;
LeaveTypeName = CASUAL;
LeaveYear = 2016;
LieuDayList = "<null>";
ModuleId = 2;
NoOfDays = 1;
ObjectId = 20;
PreApproved = 0;
Remarks = "";
RequestId = 0;
RequestStatus = P;
StartDate = "2016-08-01T00:00:00";
StartDateSession = full;
StartDateString = "08/01/2016";
Status = 0;
SystemLeaveTypeCode = CAS;
UpdatedBy = 0;
UpdatedDate = "0001-01-01T00:00:00";
}
Try
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:0
error:&jsonError];
Don't give any options.

show user's location with a custom pin on map and in a table view

i m showing user's location in a map view(apple map) with custom pin and those same pins are shown in a table view in front of the user name.Each user should have a different pin and if the user name occurs twice then it should have the same pin colour as the previous one.
This is the table view screen shot and below this table view there is a map view:
if in the table view "user name" has blue pin then in the map "username's" location shud be shown with blue pin.
if user2 has green pin in table, it should be green in map as well.
the response i m getting is
{
"driver_or_rider" = 1;
email = "ish#gmail.com";
isGuest = 0;
lat = "47.606209";
long = "-122.332071";
name = "ish bids";
"status_trip" = 1;
"user_image_url" = "http://app/image/1458101010.userimage";
},
{
"driver_or_rider" = 0;
email = "arin#gmail.com";
isGuest = 0;
lat = "34.052227";
long = "-118.243660";
name = "arin John";
"status_trip" = 1;
"user_image_url" = "http://app/image/5b3ee2e9fb51c7b20303a95b93bf63b2.";
},
{
"driver_or_rider" = 0;
email = "deepak12#gmail.com";
isGuest = 0;
lat = "31.968599";
long = "-99.901813";
name = "Deepak Chaudhary chaudhary ";
"status_trip" = 1;
"user_image_url" = "http://app/image/2197c75dc6b2bbd0ff26008a987781f3.";
},
{
"driver_or_rider" = 0;
email = "ish#gmail.com";
isGuest = 1;
lat = "31.968599";
long = "-99.901813";
name = "Deepak Chaudhary chaudhary 's Guest";
"status_trip" = 1;
"user_image_url" = "http://app/image/no-image.png";
},
{
"driver_or_rider" = 0;
email = "ish#gmail.com";
isGuest = 1;
lat = "41.878114";
long = "-87.629798";
name = "shiv Shankar 's Guest";
"status_trip" = 1;
"user_image_url" = "http://app/image/no-image.png";
},
{
"driver_or_rider" = 0;
email = "shiv#gmail.com";
isGuest = 0;
lat = "41.878114";
long = "-87.629798";
name = "shiv Shankar ";
"status_trip" = 1;
"user_image_url" = "http://app/image/1458129359.userimage";
},
{
"driver_or_rider" = 0;
email = "andrew.payasi#gmail.com";
isGuest = 0;
lat = "43.65322577127058";
long = "-79.38318371772766";
name = username;
"status_trip" = 1;
"user_image_url" = "http://app/image/1456821877.png";
}
)
this is the code in cell for row at index
int randomNumber = indexPath.row % [imageNameArray count];
NSString* nameStr=[goersInfo valueForKey:#"name"];
NSArray * nameStrArray = [nameStr componentsSeparatedByString: #"'s"];
nameStr=[nameStrArray objectAtIndex:0];
NSNumber *indexNumber = self.pinDictionary[nameStr];
index = indexNumber.unsignedIntegerValue;
cell.PinImageView.image=[UIImage imageNamed:[imageNameArray objectAtIndex:index]];
this is dictionary where name are stored
- (void)setupPinDictionary
{
self.pinDictionary = [NSMutableDictionary dictionary];
self.imageNameArray = [[NSArray alloc] initWithObjects:#"pin2#2x.png", #"pin3#2x.png", #"pin4#2x.png", #"pin5#2x.png", #"pin6#2x.png",#"pin8#2x.png",#"pin9#2x.png", nil];
NSUInteger pinImageCount = self.imageNameArray.count;
for (NSDictionary *goersInfo in tableGoersList) {
NSString* nameStr=[goersInfo valueForKey:#"name"];
NSArray * nameStrArray = [nameStr componentsSeparatedByString: #"'s"];
nameStr=[nameStrArray objectAtIndex:0];
if (self.pinDictionary[nameStr] == nil) {
indexPin = arc4random() % pinImageCount;
self.pinDictionary[nameStr] = [NSNumber numberWithUnsignedInteger: indexPin];
}
}
Initially this method is called
-(void)doJourneyGoersList:(id)responseObject{
NSDictionary *dict=[responseObject[#"Count"] firstObject];
checkLocation=[[NSMutableArray alloc]init];
if (dict==nil) {
return;
}
[_messagesButton.badgeButton setBadgeValue:dict[#"Count_Masssage"]];
[_invitesButton.badgeButton setBadgeValue:dict[#"invite_count"]];
[_matchedButton.badgeButton setBadgeValue:dict[#"Count_Match"]];
goersList= [responseObject objectForKey:#"statement"];
CLLocationCoordinate2D orginCllocation=CLLocationCoordinate2DMake([_tripDetails[#"origin_lat"] doubleValue], [_tripDetails[#"origin_long"] doubleValue]);
MKPointAnnotation *annotation =[[MKPointAnnotation alloc] init];
annotation.coordinate=orginCllocation;
[checkLocation addObject:annotation];
tableGoersList=[NSMutableArray new];
for (NSDictionary *dict in goersList) {
NSMutableDictionary *localdict=[NSMutableDictionary new];
loc=[NSMutableDictionary new];
[localdict setObject:[dict objectForKey:#"name"] forKey:#"name"];
[localdict setObject:[dict objectForKey:#"email"] forKey:#"email"];
if ([dict[#"status_trip"] isEqualToString:#"confirm"]) {
[localdict setObject:#"1" forKey:#"status_trip"];
[loc setObject:[dict objectForKey:#"origin_lat"] forKey:#"lat"];
[loc setObject:[dict objectForKey:#"origin_long"] forKey:#"long"];
CLLocationCoordinate2D location=CLLocationCoordinate2DMake([loc[#"lat"] doubleValue], [loc[#"long"] doubleValue]);
[localdict setObject:[dict objectForKey:#"origin_lat"] forKey:#"lat"];
[localdict setObject:[dict objectForKey:#"origin_long"] forKey:#"long"];
if (location.latitude == orginCllocation.latitude && location.longitude == orginCllocation.longitude) {
//location is origin, skip this since it is already added
} else {
MKPointAnnotation *annotation =[[MKPointAnnotation alloc] init];
annotation.coordinate=location;
[checkLocation addObject: annotation];
}
NSLog(#"check location %#",checkLocation);
}
else
[localdict setObject:#"0" forKey:#"status_trip"];
if ([dict[#"isGuest"] isEqualToString:#"1"]) {
[localdict setObject:#"1" forKey:#"isGuest"];
}
else
[localdict setObject:#"0" forKey:#"isGuest"];
[localdict setObject:[dict objectForKey:#"user_image_url"] forKey:#"user_image_url"];
if ([dict[#"driver_or_rider"] isEqualToString:#"Drive"]) {
[localdict setObject:#"1" forKey:#"driver_or_rider"];
[tableGoersList insertObject:localdict atIndex:0];
}
else
{
[localdict setObject:#"0" forKey:#"driver_or_rider"];
[tableGoersList addObject:localdict];
}
//add the objects to the array
}
CLLocationCoordinate2D parkCllocation=CLLocationCoordinate2DMake([_tripDetails[#"park_lat"] doubleValue], [_tripDetails[#"park_long"] doubleValue]);
MKPointAnnotation *jauntAnnotationPark =[[MKPointAnnotation alloc] init];
jauntAnnotationPark.coordinate=parkCllocation;
[checkLocation addObject:jauntAnnotationPark];
[mapView showAnnotations: checkLocation animated:NO];
[mapView setCenterCoordinate:mapView.region.center animated:NO];
int count = [checkLocation count];
CLLocationCoordinate2D coordinateArray[count];
for (int i = 0; i < count; i++) {
coordinateArray[i] = ((MKPointAnnotation *)checkLocation[i]).coordinate;
}
self.routeLine = [MKPolyline polylineWithCoordinates:coordinateArray count:count];
[mapView addOverlay:self.routeLine];
[self setupPinDictionary];
[self.ridersTableView reloadData];
}
and this is the code for view for annotation
{
imageNameArray = [[NSArray alloc] initWithObjects:#"pin2#2x.png", #"pin3#2x.png", #"pin4#2x.png", #"pin5#2x.png", #"pin6#2x.png",#"pin8#2x.png",#"pin9#2x.png",nil];
[self setupPinDictionary];
myAnnotation.image=[UIImage imageNamed:[imageNameArray objectAtIndex:indexPin]];
}
return myAnnotation;
}

Access exchange contacts on device

I have an app, that needs to get the user's contacts
providing the user gave access to the contacts
How do i get the exchange contacts ?
I tried the normal method of accessing the phone book, but i want to create my own ui
and in my own ui, only the local contacts appear
this is my code to get the contacts
- (void)reloadAddressBook
{
// Create addressbook data model
NSMutableArray *contactsTemp = [NSMutableArray array];
ABAddressBookRef addressBooks = [(TKPeoplePickerController*)self.navigationController addressBook];
CFArrayRef allPeople;
CFIndex peopleCount;
if (_group) {
self.title = _group.name;
ABRecordRef groupRecord = ABAddressBookGetGroupWithRecordID(addressBooks, (ABRecordID)_group.recordID);
allPeople = ABGroupCopyArrayOfAllMembers(groupRecord);
peopleCount = (CFIndex)_group.membersCount;
} else {
self.title = NSLocalizedString(#"All Contacts", nil);
allPeople = ABAddressBookCopyArrayOfAllPeople(addressBooks);
peopleCount = ABAddressBookGetPersonCount(addressBooks);
}
for (NSInteger i = 0; i < peopleCount; i++)
{
ABRecordRef contactRecord = CFArrayGetValueAtIndex(allPeople, i);
if (!contactRecord) continue;
CFStringRef abName = ABRecordCopyValue(contactRecord, kABPersonFirstNameProperty);
CFStringRef abLastName = ABRecordCopyValue(contactRecord, kABPersonLastNameProperty);
CFStringRef abFullName = ABRecordCopyCompositeName(contactRecord);
Contact *contact = [[Contact alloc] init];
NSString *fullNameString;
NSString *firstString = (__bridge NSString *)abName;
NSString *lastNameString = (__bridge NSString *)abLastName;
if ((__bridge id)abFullName != nil) {
fullNameString = (__bridge NSString *)abFullName;
} else {
if ((__bridge id)abLastName != nil)
{
fullNameString = [NSString stringWithFormat:#"%# %#", firstString, lastNameString];
}
}
if([fullNameString isEqualToString:#"אלי"]){
LogInfo(#"found eli");
}
contact.name = fullNameString;
contact.recordID = (int)ABRecordGetRecordID(contactRecord);
contact.rowSelected = NO;
contact.lastName = (__bridge NSString*)abLastName;
contact.firstName = (__bridge NSString*)abName;
ABPropertyID multiProperties[] = {
kABPersonPhoneProperty,
kABPersonEmailProperty
};
NSInteger multiPropertiesTotal = sizeof(multiProperties) / sizeof(ABPropertyID);
for (NSInteger j = 0; j < multiPropertiesTotal; j++) {
ABPropertyID property = multiProperties[j];
ABMultiValueRef valuesRef = ABRecordCopyValue(contactRecord, property);
NSInteger valuesCount = 0;
if (valuesRef != nil) valuesCount = ABMultiValueGetCount(valuesRef);
if (valuesCount == 0) {
CFRelease(valuesRef);
continue;
}
for (NSInteger k = 0; k < valuesCount; k++) {
CFStringRef value = ABMultiValueCopyValueAtIndex(valuesRef, k);
switch (j) {
case 0: {// Phone number
contact.tel = [(__bridge NSString*)value telephoneWithReformat];
break;
}
case 1: {// Email
contact.email = (__bridge NSString*)value;
break;
}
}
CFRelease(value);
}
CFRelease(valuesRef);
if(contact.tel.length == 0){
continue;
}
}
[contactsTemp addObject:contact];
if (abName) CFRelease(abName);
if (abLastName) CFRelease(abLastName);
if (abFullName) CFRelease(abFullName);
}
if (allPeople) CFRelease(allPeople);
// Sort data
UILocalizedIndexedCollation *theCollation = [UILocalizedIndexedCollation currentCollation];
SEL sorter = ABPersonGetSortOrdering() == kABPersonSortByFirstName ? NSSelectorFromString(#"sorterFirstName") : NSSelectorFromString(#"sorterLastName");
for (TKContact *contact in contactsTemp) {
NSInteger sect = [theCollation sectionForObject:contact
collationStringSelector:sorter];
contact.sectionNumber = sect;
}
NSInteger highSection = [[theCollation sectionTitles] count];
NSMutableArray *sectionArrays = [NSMutableArray arrayWithCapacity:highSection];
for (int i=0; i<=highSection; i++) {
NSMutableArray *sectionArray = [NSMutableArray arrayWithCapacity:1];
[sectionArrays addObject:sectionArray];
}
for (TKContact *contact in contactsTemp) {
[(NSMutableArray *)[sectionArrays objectAtIndex:contact.sectionNumber] addObject:contact];
}
for (NSMutableArray *sectionArray in sectionArrays) {
NSArray *sortedSection = [theCollation sortedArrayFromArray:sectionArray collationStringSelector:sorter];
[_listContent addObject:sortedSection];
}
[self.tableView reloadData];
}

Merge the same objects inside array IOS

I have an array which contains this objects:
(
{
aOptns = (
);
fCustomDscnt = 0;
fPrcntDscnt = 0;
fPrice = 0;
fQty = 1;
iItemDayPriceId = 143;
iShiftId = 1;
sItemName = "";
sModifier = "";
},
{
aOptns = (
);
fCustomDscnt = 0;
fPrcntDscnt = 0;
fPrice = 0;
fQty = 1;
iItemDayPriceId = 143;
iShiftId = 1;
sItemName = "";
sModifier = "";
},
{
aOptns = (
);
fCustomDscnt = 0;
fPrcntDscnt = 0;
fPrice = 0;
fQty = 1;
iItemDayPriceId = 143;
iShiftId = 1;
sItemName = "";
sModifier = "";
},
{
aOptns = (
);
fCustomDscnt = 0;
fPrcntDscnt = 0;
fPrice = 0;
fQty = 1;
iItemDayPriceId = 112;
iShiftId = 1;
sItemName = "";
sModifier = "";
}
)
I need to merge the contents of array if the objects are same and modify the object inside that array in such a way that it should be like this:
(
{
aOptns = (
);
fCustomDscnt = 0;
fPrcntDscnt = 0;
fPrice = 0;
fQty = 3;
iItemDayPriceId = 143;
iShiftId = 1;
sItemName = "";
sModifier = "";
},
{
aOptns = (
);
fCustomDscnt = 0;
fPrcntDscnt = 0;
fPrice = 0;
fQty = 1;
iItemDayPriceId = 112;
iShiftId = 1;
sItemName = "";
sModifier = "";
}
)
As you can see, the entry for object with iItemDayPriceId = 143 becomes 1 only with fQty = 3.
I have tried using the code here: How to Find Duplicate Values in Arrays?
But it is only comparing 2 objects at a time.
Edit: Oops, I missed your count requirement.
Edit 2: And the fact that you wanted to mutate the given array rather the build a new one.
Depends on what you mean by distinct but since it looks like you mean to compare the contents and not the references, you should build a new array so that if the comparison is true you increment the count and otherwise you add the object.
Mutate existing array
Disclaimer: probably not my best work here.
I would appreciate if someone could suggest how to improve this because I am pretty sure it is not the best way to do this and may not even work (don't have access to an Obj-C compiler at the moment).
Foo objectA = [Foo new];
objectA.Bar = #"Bar";
Foo objectB = [Foo new];
objectB.Bar = #"Bar";
Foo objectC = [Foo new];
objectC.Bar = #"Not Bar";
NSMutableArray *array = #[objectA, objectB, objectC];
NSMutableDictionary *countDictionary = [[NSMutableDictionary alloc] init];
for (Foo *foo in [array copy])
{
bool found = false;
for (Foo *key in countDictionary)
{
if ([key isEqualTo:foo])
{
NSNumber *currentCount = [countDictionary objectForKey:key];
int currentIntCount = [currentCount intValue];
currentIntCount++;
[countDictionary setObject:[NSNumber numberWithInt:currentIntCount] forKey:key];
[array removeObject:key];
found = true;
break;
}
if (!found)
[countDictionary setObject:[NSNumber numberWithInt:1] forKey:foo];
}
}
for (Foo *realFoo in array)
{
NSNumber *countNumber = [countDictionary objectForKey:realFoo];
int countInt = [countNumber intValue];
realFoo.Count = countInt;
}
Build new array
Foo objectA = [Foo new];
objectA.Bar = #"Bar";
Foo objectB = [Foo new];
objectB.Bar = #"Bar";
NSMutableArray *array = #[objectA, objectB];
NSMutableArray *distinct = [[NSMutableArray alloc] init];
for (Foo *f in array)
{
bool found = false;
for (Foo *d in distinct)
{
if ([d isEqualTo:f])
{
found = true;
d.Count++;
}
break;
}
if (!found)
[distinct addObject:f];
}
And of course you would have to define an equality comparer for Foos, in this case for instance
-(bool) isEqualTo:(Foo *)nFoo
{
bool isEqual = false;
if ([self.Bar isEqualToString:nFoo.Bar])
isEqual = true;
return isEqual;
}
Having not dealt with Objective C in a while I should say that there may be some best-practices as to implementing equality comparison instead of rolling your own completely like this example
Use below code:
NSMutableArray* myArray =
[[NSMutableArray alloc]initWithObjects:
#"red",#"blue",#"red",#"green",#"yellow", #"33", #"33",#"red", #"123", #"123",nil];
NSOrderedSet *mySet = [[NSOrderedSet alloc] initWithArray:myArray];
myArray = [[NSMutableArray alloc] initWithArray:[mySet array]];
NSLog(#"%#",myArray);

Resources