pass value array for sectioned uitableview - ios

I am facing difficulties on passing a value on array for sectioned UITableView
This code works well for me
LandingMenu *landing0 = [[LandingMenu alloc]init];
[landing0 setMenuTitle:#"For Verification"];
[landing0 setMenuTotalCount:[NSString stringWithFormat:#"%i",20]];
[landing0 setMenuColorCode:[NSNumber numberWithInt:0]];
LandingMenu *landing6 = [[LandingMenu alloc]init];
[landing6 setMenuTitle:#"For Approval"];
[landing6 setMenuTotalCount:[NSString stringWithFormat:#"%i",5]];
[landing6 setMenuColorCode:[NSNumber numberWithInt:0]];
_taskList = [NSMutableArray arrayWithObjects:landing0, landing6, nil];
LandingMenu *landing1 = [[LandingMenu alloc]init];
[landing1 setMenuTitle:#"Fund Transfer Own"];
[landing1 setMenuTotalCount:[NSString stringWithFormat:#"%i",9]];
[landing1 setMenuType:[NSNumber numberWithInt:0]];
LandingMenu *landing2 = [[LandingMenu alloc]init];
[landing2 setMenuTitle:#"Fund Transfer Third Party"];
[landing2 setMenuTotalCount:[NSString stringWithFormat:#"%i",5]];
[landing2 setMenuType:[NSNumber numberWithInt:0]];
LandingMenu *landing3 = [[LandingMenu alloc]init];
[landing3 setMenuTitle:#"Checkbook Reorder"];
[landing3 setMenuTotalCount:[NSString stringWithFormat:#"%i",5]];
[landing3 setMenuType:[NSNumber numberWithInt:1]];
LandingMenu *landing4 = [[LandingMenu alloc]init];
[landing4 setMenuTitle:#"Stop Payment Order"];
[landing4 setMenuTotalCount:[NSString stringWithFormat:#"%i",6]];
[landing4 setMenuType:[NSNumber numberWithInt:0]];
_forVerificationList = [NSMutableArray arrayWithObjects:landing1, landing2, landing4, nil];
_forApprovalList = [NSMutableArray arrayWithObjects:landing3, nil];
[_menuList addObject:[[NSArray alloc] initWithObjects:landing1, landing2, landing4, nil]];
[_menuList addObject:[[NSArray alloc] initWithObjects:landing3, nil]];
Now, i'm having a problem how to convert something like the one specified above having output. Assuming that this code came from a JSON object.
for (NSDictionary *dictCQ in taskJson) {
NSLog(#"TASKLIST: %#", [dictCQ objectForKey:#"foTaskListModelWs"]);
NSDictionary *datadic = [dictCQ objectForKey:#"foTaskListModelWs"];
TaskList *task = [[TaskList alloc]init];
[task setCount:datadic[#"count"]];
[task setFuncCd:datadic[#"funcCd"]];
[task setFuncCdDscp:datadic[#"funcCdDscp"]];
[task setRequestStatus:datadic[#"requestStatus"]];
[task setRole:datadic[#"role"]];
[taskList addObject:task];
}

Related

How to retrieve specific value of key in json?

this is my json content.
[
{
"sha":"30eae8a47d0203ac81699d8fc2ab2632de2d0bba",
"commit":{
"author":{
"name":"Madhura Bhave",
"email":"mbhave#pivotal.io",
"date":"2017-03-23T23:14:32Z"
},
"committer":{
"name":"Madhura Bhave",
"email":"mbhave#pivotal.io",
"date":"2017-03-23T23:14:32Z"
},
"message":"Merge branch '1.5.x'",
}
}
]
and this is my main.i just want to retrieve key value from message and name,email,date from committer dictionary.i got stuck how to do that.
NSMutableArray *CommitArray = [[NSMutableArray alloc] init];
for (NSDictionary *CommitDictionary in CommitJson) {
CommitDict *commitDictObj = [[CommitDict alloc] init];
commitDictObj.message = [CommitDictionary objectForKey:#"message"];
for (NSDictionary *CommitterDictionary in [CommitDictionary objectForKey:#"committer"]) {
Committer *author = [[Committer alloc] init];
author.name = [CommitterDictionary objectForKey:#"name"];
author.email = [CommitterDictionary objectForKey:#"email"];
author.date = [CommitterDictionary objectForKey:#"date"];
}
[CommitArray addObject:commitDictObj];
}
for (int i =0 ; i < [CommitArray count] ; i++){
CommitDict *commitDictObj = [CommitArray objectAtIndex:i];
NSLog(#"Commit Message: %#", commitDictObj.message);
}
return 0;
}
}
i try fetch the json and display it value of message,name,email and date.how can i log the value of message, name, email and date?
Your array contains a dictionary, and that dictionary contains the commit dictionary, not the commit dictionary directly. Replace that part of your code:
for (NSDictionary *CommitDictionary in CommitJson) {
CommitDict *commitDictObj = [[CommitDict alloc] init];
With that:
for (NSDictionary *shaCommitDictionary in CommitJson) {
CommitDict *commitDictObj = [[CommitDict alloc] init];
NSDictionary *CommitDictionary = [shaCommitDictionary objectForKey:#"commit"];
(1) Convert JSON to NSDictionary
NSData *jsonData= ... // Assume you got the data already loaded
NSError *error = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
(2) Access the dictionary values (fast enumeration available by now!!
NSString *message = dictionary[#"message"];
NSDictionary *author = dictionary[#"author"];
NSString *name = author[#"author"];
NSString *email = author[#"author"];
NSString *date = author[#"author"];
// OR:
// NSString *name = dictionary[#"author"][#"author"];
// NSString *email = dictionary[#"author"][#"author"];
// NSString *date = dictionary[#"author"][#"author"];
And thats it. I think the tricky thing is to get the JSON Data to the NSDictionary?
See here: https://stackoverflow.com/a/30561781/464016

Save json object in sqlite like text and retransform to dictionary on read

I want to save a Json Object in a field (text) sqlite and then read it again with a select and retransform to NSDictionary or NSMutableArray to parse the key/values
This is how i save actually in the sqlite DB
As you see, is a song object from the iTunes api. I want to read that object and parse it.
This is how i make the select query and save it in a NSDictionary while i filling and NSMutableArary
globals.arrayMyPlaylists = [[NSMutableArray alloc] init];
// Form the query.
NSString *query = #"select * from myplaylists";
// Get the results.
NSArray *listas = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
for (int i = 0; i < listas.count; i++) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
NSLog(#"lista %d %# %#", i, listas[i][0], listas[i][1]);
[dictionary setObject:listas[i][0] forKey:#"id"];
[dictionary setObject:listas[i][1] forKey:#"nombre"];
NSString *query2 = [NSString stringWithFormat:#"select cancion from canciones where idplaylist = %#", listas[i][0]];
NSArray *canciones = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query2]];
[dictionary setObject:canciones forKey:#"canciones"];
[globals.arrayMyPlaylists addObject:dictionary];
dictionary = nil;
}
When i try to read it in the cellForRowAtIndexPath method
NSArray *canciones = [[NSArray alloc] initWithArray:[[globals.arrayMyPlaylists objectAtIndex:indexPath.row] valueForKey:#"canciones"]];
and try to get the value for the key artworkUrl100
[cell.tapa1 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#", [[canciones objectAtIndex:i] valueForKey:#"artworkUrl100"]]] placeholderImage:nil];
i get the error
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x7ff575810600> valueForUndefinedKey:]: this class is not key value coding-compliant for the key artworkUrl100.'
i understand i'm messing up in some way with dictionarys/nsmutablearrays. I need some help. Thanks!
EDIT: this is how i save the data in the DB
NSString *query = [NSString stringWithFormat:#"insert into canciones (idplaylist, cancion) values ('%#', '%#')", [[globals.arrayMyPlaylists objectAtIndex:indexPath.row] valueForKey:#"id"], self.elementoSeleccionado];
[self.dbManager executeQuery:query];
self.elementoSeleccionado is the NSMutableArray with the "cancion" object and it's saved like it's shows the first image.
EDIT 2: this is what i get trying schmidt9's answer
EDIT 3: OK, i have the json string escaped. How i have to parse now?
You should parse your output first with NSJSONSerialization:
NSString *query2 = [NSString stringWithFormat:#"select cancion from canciones where idplaylist = %#", listas[i][0]];
NSArray *canciones = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query2]];
// I suppose your array canciones should contain only one song object ...
NSError *error = nil;
id object = [NSJSONSerialization JSONObjectWithData:canciones[0] options:0 error:&error];
if(error) {
// handle error ...
}
if([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *result = object;
[dictionary setObject:result forKey:#"canciones"];
}
Edit
Saving to database
2 options:
- if you get a prepared json string, save it directly to DB, but before you should escape quotes. See eg. here
- if you have NSDictionary:
- (NSString*)JSONStringWithDictionary:(NSDictionary*)dictionary prettyPrinted:(BOOL)prettyPrinted
{
NSJSONWritingOptions options = (prettyPrinted) ? NSJSONWritingPrettyPrinted : 0;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:options error:nil];
return [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
}
After that you should escape the string too.

Create Events for MBCalendarKit in iOS

I imported MBCalendar Kit into my project, and I don't know how to add an event or array of events in calendar. I found this code:
NSMutableDictionary *eventsDict = [[NSMutableDictionary alloc] init];
for (int i =0; i< eventsArray.count ;i++)
{
// Create events
eventsDict = eventsArray[i];
CKCalendarEvent* aCKCalendarEvent = [[CKCalendarEvent alloc] init];
aCKCalendarEvent.title = [eventsDict objectForKey:#"email"];
aCKCalendarEvent.date = date; //[eventsArray objectForKey:#"phone"];
aCKCalendarEvent.address = [eventsDict objectForKey:#"addrLine1"];
aCKCalendarEvent.image = [eventsDict objectForKey:#"pPic"];
aCKCalendarEvent.name = [eventsDict objectForKey:#"fname"];
aCKCalendarEvent.appDate = [eventsDict objectForKey:#"apntDt"];
aCKCalendarEvent.notes = [eventsDict objectForKey:#"notes"];
aCKCalendarEvent.phone = [eventsDict objectForKey:#"phone"];
[myeventsArray addObject: aCKCalendarEvent];
}
[_data setObject:myeventsArray forKey:date];
but I don't know where to write it, or how to use it. Can anyone help me?
Thank you.
I'm working with this Framework and I've had the same issues.
What worked for me was to use the NSDate+Components category, specifically the dayWithDay:month:year method to create the dates for the events, then create as many events as you want the way you're doing it, encapsulate all the events that are on the same day in an array and lastly setting that array as an object for the NSDictionary data with the previously created as the key to that array. Here's an example:
NSDate *eventDate1 = [NSDate dateWithDay:8 month:8 year:2014];
NSDate *eventDate2 = [NSDate dateWithDay:9 month:8 year:2014];
CKCalendarEvent *event1 = [CKCalendarEvent eventWithTitle:#"Event 1" andDate:eventDate1 andInfo:nil];
CKCalendarEvent *event2 = [CKCalendarEvent eventWithTitle:#"Event 2" andDate:eventDate2 andInfo:nil];
NSArray *today = [NSArray arrayWithObjects:event1, nil];
NSArray *tomorrow = [NSArray arrayWithObjects:event2, nil];
[[self data] setObject:today forKey:eventDate1];
[[self data] setObject:tomorrow forKey:eventDate2];
Hope this helps :D
I'm working on my own framework based on this but with an iOS7 native feel, it's not finished yet but here is the repo:
https://github.com/AndoniV/CalendarBar_iOS7_Style.git

convert array format according to array character

I have array in this format
rows = [[NSArray alloc] initWithObjects:#"adam", #"alfred", #"ain", #"abdul", #"anastazja", #"angelica",
#"dennis" , #"deamon", #"destiny", #"dragon", #"dry", #"debug" #"drums",
#"Fredric", #"France", #"friends", #"family", #"fatish", #"funeral",
#"Mark", #"Madeline",
#"Nemesis", #"nemo", #"name",
#"Obama", #"Oprah", #"Omen", #"OMG OMG OMG", #"O-Zone", #"Ontario",
#"Zeus", #"Zebra", #"zed", nil];
But i need this in to following format
rows = #[#[#"adam", #"alfred", #"ain", #"abdul", #"anastazja", #"angelica"],
#[#"dennis" , #"deamon", #"destiny", #"dragon", #"dry", #"debug", #"drums"],
#[#"Fredric", #"France", #"friends", #"family", #"fatish", #"funeral"],
#[#"Mark", #"Madeline"],
#[#"Nemesis", #"nemo", #"name"],
#[#"Obama", #"Oprah", #"Omen", #"OMG OMG OMG", #"O-Zone", #"Ontario"],
#[#"Zeus", #"Zebra", #"zed"]];
Means that same starting character in to different dictionary
The easiest approach.
NSArray *rows = ...;
NSMutableDictionary *map = [NSMutableDictionary dictionary];
for (NSString *value in rows) {
NSString *firstLetter = [value substringToIndex:1];
if (!map[firstLetter]) {
map[firstLetter] = #[];
}
NSMutableArray *values = [map[firstLetter] mutableCopy];
[values addObject:value];
map[firstLetter] = values;
}
NSArray *finalRows = [map allValues];
Note that finalRows is not sorted.
If you want to sort your array by it's first letter, you can try this :
NSMutableArray *outputArray = [NSMutableArray new];
NSString *lastFirstLetter = nil;
for(NSString *value in rows) {
NSString *firstLetter = [[value substringToIndex:1] lowerString];
if(![lastFirstLetter isEqualToString:firstLetter]) {
lastFirstLetter = firstLetter;
[outputArray addObject:[NSMutableArray new]];
}
[[outputArray lastObject] addObject:value];
}
The idea is to iterate your input array and if the first letter of your word is different than the precedent, create a new array.

Why is my array returning null?

I am calling getBoardingCards once here:
BRPBoardingCards *boardingCards = [[BRPBoardingCards alloc] init];
boardingCardsArray = [boardingCards getBoardingCards];
The array is returning null though (in the NSLog shown). What am I doing wrong?
- (NSArray*)getBoardingCards
{
NSMutableArray *storedArray = [[NSMutableArray alloc] init];
Utils *utils = [[Utils alloc] init];
NSUserDefaults *properties = [utils getUserDefaults];
// check if its the first time we are running the app.
if(![[properties objectForKey:#"first_run"] isEqualToString:#"no"]){
//I decided it is for american tourists and every booking office allows payment in dollars because I dont have a euros key on my keyboard.
//Car also has lots of seats. 1337 of them to be precise.
[self setNewBoardingCardWithCardType:#"car" WithPrice:#"$1.50" AndStartLocation:#"airport" AndEndLocation:#"restaurant" WithSeat:#"1337" andExtraInformation:#"We dont like you so we are giving you the back seat by yourself."];
[self setNewBoardingCardWithCardType:#"helicopter" WithPrice:#"$500" AndStartLocation:#"restaurant" AndEndLocation:#"hospital" WithSeat:#"1" andExtraInformation:#"You are driving."];
[self setNewBoardingCardWithCardType:#"train" WithPrice:#"$100" AndStartLocation:#"restaurant" AndEndLocation:#"ditch" WithSeat:#"STANDONHEAD" andExtraInformation:#"No Seats on this train. Gotta stand on your head. Dont forget your white lightning for the ditch."];
[self setNewBoardingCardWithCardType:#"Fire Engine" WithPrice:#"$10" AndStartLocation:#"restaurant" AndEndLocation:#"burning house" WithSeat:#"HOSE" andExtraInformation:#"Take the hose to put out this fire we are heading to. "];
[self setNewBoardingCardWithCardType:#"Nimbus" WithPrice:#"$300" AndStartLocation:#"burning house" AndEndLocation:#"popo floating island" WithSeat:#"LEVITATION" andExtraInformation:#"Dont forget to turn super saiyan on your way up there. "];
[self setNewBoardingCardWithCardType:#"Sky Dive" WithPrice:#"$1020" AndStartLocation:#"popo floating island" AndEndLocation:#"home" WithSeat:#"GRAVITY" andExtraInformation:#"Ohh! that Adrenalines pumping. "];
[self setNewBoardingCardWithCardType:#"Legs" WithPrice:#"$50" AndStartLocation:#"ditch" AndEndLocation:#"park bench hotel" WithSeat:#"VODKA" andExtraInformation:#"Time to get a good nights rest and sobre up. "];
[self setNewBoardingCardWithCardType:#"Bicycle" WithPrice:#"$5" AndStartLocation:#"park bench hotel" AndEndLocation:#"home" WithSeat:#"BIKESEAT1" andExtraInformation:#"What a terrible hangover. Time to head home. "];
[self setNewBoardingCardWithCardType:#"ambulance" WithPrice:#"$40" AndStartLocation:#"hospital" AndEndLocation:#"home" WithSeat:#"LEVITATION" andExtraInformation:#"Well that was a bad idea! "];
[properties setObject:#"no" forKey:#"first_run"];
[properties synchronize];
NSLog(#"did set first run to no");
}
storedArray = [[properties objectForKey:#"cards"] mutableCopy];
NSLog(#"getBoardingCards storedArray: %#", storedArray);
return storedArray;
}
- (NSArray*)getBoardingCardsByType:(NSString*)cardType
{
// at this point i would create a for loop and iterate through the array checking if (type isEqualToString:cardType).
// But this is just an idea for later. To go by only a certain type of route.
return nil;
}
- (void)setNewBoardingCardWithCardType:(NSString*)cardType WithPrice:(NSString*)price AndStartLocation:(NSString*)startLocation AndEndLocation:(NSString*)endLocation WithSeat:(NSString*)seatCode andExtraInformation:(NSString*)extraInfo{
// populate the dictionary with data.
NSMutableDictionary *card = [[NSMutableDictionary alloc] init];
[card setObject:cardType forKey:#"type"];
[card setObject:price forKey:#"price"];
[card setObject:startLocation forKey:#"startLocation"];
[card setObject:endLocation forKey:#"endLocation"];
[card setObject:seatCode forKey:#"seat"];
[card setObject:extraInfo forKey:#"info"];
// get our stored array.
Utils *utils = [[Utils alloc] init];
NSUserDefaults *properties = [utils getUserDefaults];
NSMutableArray *storedArray = [[properties objectForKey:#"cards"] mutableCopy];
[storedArray addObject:card];
// set the stored array.
[properties setObject:storedArray forKey:#"cards"];
[properties synchronize];
}
You're not creating the cards mutable array in the NSUserDefaults.
This line (in setNewBoardingCardWithCardType:):
NSMutableArray *storedArray = [[properties objectForKey:#"cards"] mutableCopy];
is essentially
NSMutableArray *storedArray = [nil mutableCopy];
which is the same as
NSMutableArray *storedArray = nil;
Check if the object for this key exist, if not - create it and then use it.

Resources