For loop not changing variables - ios

First post here, so just wanted to say hi. Im a starting iOs developer, just for fun though.
Ive been breaking my head over the following code:
for (int n = 0; n <= iterations; n = n + 1) {
int interval = [[object valueForKey:#"interval"] integerValue];
NSTimeInterval singeltonTimestamp = interval * n;
NSLog(#"%d",(int)singeltonTimestamp);
[skeleton removeObjectForKey:#"date"];
[skeleton setObject:[[object objectForKey:#"start"] dateByAddingTimeInterval:singeltonTimestamp] forKey:#"date"];
[yuups addObject:skeleton];
NSLog(#"adding skeleton");
}
I have an object called skeleton and I am trying to add 4 of them (iterations = 3) with the date increasing with a certain interval. The singeltonTimestamp changes correctly (reading the NSLog output) but the date's for the skeletons are all the same, they dont increase.
"Object" contains a start date and an interval, I set some stuff (like the title) for the skeleton beforehand.
See this output
014-04-12 14:32:38.676 yuup[8397:60b] (
{
date = "2014-04-15 18:02:00 +0000";
title = test;
},
{
date = "2014-04-15 18:02:00 +0000";
title = test;
},
{
date = "2014-04-15 18:02:00 +0000";
title = test;
},
{
date = "2014-04-15 18:02:00 +0000";
title = test;
}
)
Help or tips are much appriciated. Thanks in advance

Try this
skeleton = [NSMutableDictionary dictionary];
[skeleton setObject:[[object objectForKey:#"start"] dateByAddingTimeInterval:singeltonTimestamp] forKey:#"date"];
[yuups addObject:skeleton];
You are adding same object again and again.. You have to make new instance before adding to the NSMutableArray

Related

Getting Value from Dictionary

data = (
{
date = "2016-01-20";
"end_time" = "11:10:00";
"function_code" = RCV;
"operator_id" = JOHN;
"start_time" = "11:00:00";
"total_time" = 10;
"total_units" = 19;
},
{
date = "2016-01-20";
"end_time" = "12:25:00";
"function_code" = PIK;
"operator_id" = JOHN;
"start_time" = "12:15:00";
"total_time" = 10;
"total_units" = 26;
}
)
this array containing 2 dictionary ,i have to get the endtime from the first dictionary and starttime from the second dictionary and i want to calculate the break time from this value.i know how to get the value dictionary . data[0][#"end_time"] and data[1][#"start_time"] this is sufficient if array contains two elements .but if array has more than 5 means,i want to iterate the array .i will update my code what i did ...
my array name is arrData
for (int i 0; i<arrData.count; i++) {
dictData =arrData[i];
NSString *startTime =[dictData objectForKey:#"start_time"];
NSString *totalTime = [dictData objectForKey:#"total_time"];
NSNumber *numTotalUnits =[dictData objectForKey:#"total_units"];
NSString *functionCode = [dictData objectForKey:#"function_code"];
NSString *endTime = [dictData objectForKey:#"end_time"];
NSLog(#"%#",endTime);
[array1 addObject:endTime];
if (arrData[i+1] > arrData.count) {
dictData = arrData[i+1];
NSLog(#"%#",dictData);
NSString *strStartTime = [dictData objectForKey:#"start_time"];
NSLog(#"%#",strStartTime);
[array1 addObject:strStartTime];
NSLog(#"%#",array1);
}
}
i tried this coding but i got error like index 2 beyond bounds[0..1]
Try for (int i = 0; i < arrData.count - 1; i++) {.
In your current code, you let i become equal to arrData.count - 1 in the loop, which means that when you check i + 1 you're looking past the final array element.

How do I access elements in this dataset using objc?

I'm struggling with this dataset:
stopsArray: (
(
{
DistanceFromStart = 0;
Ordinal = 1;
Stop = {
Lat = "38.90282440185547";
Lon = "-77.03208160400391";
OrgAbbr = "<null>";
OrgId = DcCi;
StopCode = 1001259;
StopId = "DcCi_1445_7727";
StopName = "NW 14TH ST & NW K ST";
};
},
{
DistanceFromStart = "0.443314063224555";
Ordinal = 2;
Stop = {
Lat = "38.90834426879883";
Lon = "-77.03208923339844";
OrgAbbr = "<null>";
OrgId = DcCi;
StopCode = 1001393;
StopId = "DcCi_1445_7808";
StopName = "NW 14TH ST & NW RHODE ISLAND AV";
};
},
{
DistanceFromStart = "1.050716048463951";
Ordinal = 3;
Stop = {
Lat = "38.91703033447266";
Lon = "-77.03196716308594";
OrgAbbr = "<null>";
OrgId = DcCi;
StopCode = 17348;
StopId = "DcCi_1445_6674";
StopName = "NW 14TH ST & NW U ST";
};
},
I'm not sure if this is an array, a dictionary, or a combination. How do I tell the difference?
How would I pull out the "Ordinal" field, as well as elements in the "Stop" dataset?
To get the stopsArray data, I used this line:
stopsArray = [variantArray valueForKey:#"Stops"];
I've tried to pull the first Ordinal field (i.e. 1) with this:
NSMutableArray *array = stopsArray[0];
NSString *string = [array valueForKey:#"Ordinal"];
NSLog(#"string: %#", string);
But that results in:
string: (
1,
2,
3,
4,
5,
6,
7
)
Any ideas to stop my hair coming out would be most welcome.
I'll keep at it meanwhile.
Firstly, its an array of objects of type dictionary.
Secondly, the data doesn't seem to be properly formatted.
Its like an array with a single object of type dictionary, but that single object contains all the different dictionary values.
hence your result of
string: (
1,
2,
3,
4,
5,
6,
7
)
What seems to me the problem is the second open bracket
stopsArray: (
(
{
Try doing this...
NSMutableArray *array = stopsArray[0];
NSMutableArray *actualDataArray = array[0];
and then
NSString *string = [actualDataArray[INDEX_OF_DIC_OBJECT] valueForKey:#"Ordinal"];
NSLog(#"string: %#", string);
Lemme know if it works.
Updated Solution
What eventually worked for David DelMonte.
NSString *string = [[[stopsArray objectAtIndex:0] objectAtIndex:0] objectForKey:#"Ordinal"];

Save multiple values with same keys in NSMutableDictionary then store the dictionary in NSMutableArray

I know this question has been asked many times but not got the solution or i might not understood that's why posting the question.
for (int web=0; web<[web_arr count]; web++) {
AdditionalBookmark *web_book=[[AdditionalBookmark alloc]init];
UITextField *txtNam = (UITextField*)[self.view viewWithTag:1100+web];
NSString *txtName = txtNam.text;
UITextField *txtLin = (UITextField*)[self.view viewWithTag:1200+web];
NSString *txtLink = txtLin.text;
if ((txtName && txtName.length > 0)||(txtLink && txtLink.length > 0))
{
web_book.additionalBookmark_Name = txtName;
web_book.additionalBookmark_Link= txtLink;
web_book.contactDetails_Id=self.contactDetailsinfo.contactDetailsId;
web_book.additionalBookmark_Id=[[[web_arr objectAtIndex:web] valueForKey:#"WeblinkId"] intValue];
[dictWebLinks setObject:txtName forKey:#"WeblinkName"];
[dictWebLinks setObject:txtLink forKey:#"WeblinkUrl"];
[arrForWebLinks addObject:dictWebLinks];
}
[db updateIntoAdditionalBookmarkWithObject:web_book];
}
[dictUpdate setObject:arrForWebLinks forKey:#"Weblink"];
The problem am facing is this suppose there are two items in the array
Printing description of web_arr:
<__NSArrayM 0x170e4db60>(
{
WeblinkId = 9;
WeblinkName = Hdhd;
WeblinkUrl = "ie.comh";
},
{
WeblinkId = 10;
WeblinkName = Hd;
WeblinkUrl = "nd.com";
}
)
what i am getting is below:
Printing description of arrForWebLinks:
<__NSArrayM 0x170e4db30>(
{
WeblinkName = Hd;
WeblinkUrl = "nd.com";
},
{
WeblinkName = Hd;
WeblinkUrl = "nd.com";
}
)
dictionary is replacing the value for same key holding the latest value only, how can i mange to save the values in same format as in web_arr.
Any help is appreciable.
You are adding the same dictionary to the array over and over:
[dictWebLinks setObject:txtName forKey:#"WeblinkName"];
[dictWebLinks setObject:txtLink forKey:#"WeblinkUrl"];
[arrForWebLinks addObject:dictWebLinks];
You need to create a new one each time:
[arrForWebLinks addObject:#{
#"WeblinkName" : txtName,
#"WeblinkUrl" : txtLink
}];
(and remove dictWebLinks).

Group NSDictionary by dates [duplicate]

This question already has answers here:
Grouping NSArray of NSDictionary based on a key in NSDictionay
(2 answers)
Closed 8 years ago.
I have a NSDictionary and i want to group it creating an array of objects by date
Example of the main NSDictionary:
({
date = "2014-04-27";
group = "yellow.png";
length = 180;
},
{
date = "2014-04-28";
group = "blue.png";
length = 180;
},
{
date = "2014-04-27";
group = "blue.png";
length = 120;
})
I want to group something similar as:
2014-04-27 = (
{
date = "2014-04-27";
group = "yellow.png";
length = 180;
},
{
date = "2014-04-27";
group = "blue.png";
length = 180;
})
2014-04-28 = ( {
date = "2014-04-28";
group = "blue.png";
length = 120;
})
Could someone help me? i have tried many FOR but i cant get it
It appears as though your original data structure is an array of dictionaries. Was your question phrased incorrectly? I see each individual dictionary but they are not keyed on anything in the top level data structure.
Assuming that is the case (you have an array called originalArray
NSMutableDictionary *dictionaryByDate = [NSMutableDictionary new];
for(NSDictionary *dictionary in originalArray)
{
NSString *dateString = dictionary[#"date"];
NSMutableArray *arrayWithSameDate = dictionaryByDate[dateString];
if(! arrayWithSameDate)
{
arrayWithSameDate = [NSMutableArray new];
dictionaryByDate[dateString] = arrayWithSameDate;
}
[arrayWithSameDate addObject: dictionary];
}
By the end of this, dictionaryByDate will be a dictionary (keyed on date) of arrays (all objects in a given array will be dictionaries with the same date).

Sequentially ordered NSMutableArray - replacing breaks in order

I've been having a mind blank over this problem, so I thought maybe some of you could shed a light on the situation.
To cut a long story short, I am building an app that fetches a school student's timetable from a server, parses it, and displays it in a table view. Each student has 7 periods per day, and there are 10 days in the timetable spanning across a fortnight (5 days in Week A, 5 days in Week B).
However the problem lies where some students have free periods - that is, they do not have a class during that period. Because the server does not take free periods into account, some students might return 70 total periods in the fortnight, whereas another might return 66.
Cutting to the chase here...
I have an ordered NSMutableArray full of NSDictionaries. A typical object in the array would look like this when outputted to the console:
{
weekday = 12;
period = 1;
room = "Room D404";
title = "English Extension";
},
I need to figure out where there is a break in the order, and if so, insert an object into it to fill the blank. Let me give you an example:
{
dayweek = 12;
period = 1;
room = "Room D404";
title = "English Extension";
},
{
dayweek = 12;
period = 2;
room = "Room W285";
title = "Modern History";
},
{
dayweek = 12;
period = 3;
room = "Room W187";
title = "Maths Extension 1";
},
{
dayweek = 12;
period = 4;
room = "Room W370";
title = Economics;
},
{
dayweek = 12;
period = 6;
room = "Room D301";
title = "English Advanced";
},
{
dayweek = 12;
period = 7;
room = "Room W282";
title = "Studies of Religion";
},
{
dayweek = 13;
period = 1;
room = "Room W370";
title = Economics;
},
There is no object where period = 5, so I need to add one. Is what I'm saying hard to understand? Sorry if it is.
Thanks in advance!
This fills in missing periods from 1 to the last existing on a day. It does not fill days to a given minimum of periods.
NSMutableArray periods; // from somewhere else
NSUInteger count = [periods count];
NSUInteger currentPeriod = 0;
NSUInteger currentDayweek = 0;
for (NSUInteger i = 0; i < count; ++i)
{
NSDictionary *periodDescription = periods[i];
NSUInteger dayweek = [periodDescription[#"dayweek"] unsignedIntegerValue];
if (dayweek != currentDayweek) {
// another day
currentPeriod = 0;
currentDayweek = dayweek;
}
NSUInteger period = [periodDescription[#"period"] unsignedIntegerValue];
currentPeriod += 1;
while (period > currentPeriod) {
NSDictionary *fillIn = #{ #"dayweek" : #(dayweek), #"period" : #(currentPeriod), #"room" : #"cafeteria", #"title" = "taking a break" };
[periods insertObject:fillIn atIndex:i];
currentPeriod += 1;
i += 1;
count += 1;
}
}
If you do not want to fill morning hours before the first existing period, add this directly before the while loop:
if (currentPeriod == 1)
currentPeriod = period;
Note: Typed in browser, errors are probable.
Try this and let me know if you are getting any issues
for (int i = 1; i<=self.arrayForRows.count; i++)
{
if ([[[self.arrayForRows objectAtIndex:i]valueForKey:#"period"] intValue] == i)
{
}
else
{
// Insert Here as [self.arrayForRows insertObject:yourObject atIndex:i];
i=i-1;
}
}
This is only a partial answer, but too long to post as a comment.
The purpose of this snippet is only to identify missing periods with a minimal amount of code. You would need to do it in a loop for all days of the fortnight, of course.
To do this you can use predicates:
// For each day create a list of all periods.
// This is just a hard coded example
NSArray *allPeriodsForDay = #[#(1),#(2),#(3),#(4),#(5),#(6)];
// Get an array of the periods actually in the list
// It will look like this: #[#(1),#(2),#(4),#(5),#(6)]; // Period 3 missing
NSArray *studentsPeriods = [periodRecords valueForKey: #"period"];
// Build a predicate to identify period(s) not in list
NSPredicate *freePredicate = [NSPredicate predicateWithFormat:#"not self in %#", studentsPeriods];
NSArray *freePeriods = [allPeriodsForDay filteredArrayUsingPredicate:freePredicate];
freePeriods now contains a list of the "missing" periods in the students' schedule for that day.
You can then create a new NSDictionary and add it to the list. Then sort it all by the period field.

Resources