I am very new to programming in Objective C (as in a few days), and unfortunately have an iPhone app due as a project for a class in a few days (in retrospect I probably should have chosen something different). One of the main features my app needs is the ability to select a dish from a menu by first selecting the meal on one page, and then the category on the next page, and then the dish on the final page. I have gotten my app to download a JSON file from an internet API and store it as an NSArray variable, but now I need to use that array to populate my tableview. Below is a sample from the downloaded array from my app's debug window. I already have the basic framework of the app (i.e. several different views) in place. This came from a sample app that populates the tableview rows with data from a plist file, but I want to use this JSON data. How would I use this array to populate the rows with the JSON data stored in this NSArray variable?
Thanks!
2012-12-05 03:29:48.973 MLBMobile[3858:c07] {
category = "BREAKFAST MEATS";
date = "2012-12-05";
meal = BREAKFAST;
name = "Low-Sodium Ham";
portion = 1;
recipe = 319044;
unit = oz;
}
2012-12-05 03:29:48.975 MLBMobile[3858:c07] {
category = "BREAKFAST MEATS";
date = "2012-12-05";
meal = BREAKFAST;
name = "Roasted Low-Sodium Turkey";
portion = 4;
recipe = 113503;
unit = oz;
}
2012-12-05 03:29:48.976 MLBMobile[3858:c07] {
category = "BREAKFAST ENTREES";
date = "2012-12-05";
meal = BREAKFAST;
name = "Cheddar Cheese";
portion = 1;
recipe = 130029;
unit = oz;
}
2012-12-05 03:29:48.976 MLBMobile[3858:c07] {
category = "BREAKFAST ENTREES";
date = "2012-12-05";
meal = BREAKFAST;
name = "Hard Cooked Eggs - Cage Free";
portion = 1;
recipe = 061009;
unit = each;
}
With your array variable you can iterate through each element. Use fast enumeration:
for(NSDictionary *dict in yourArrayVariable){
NSString *category = [dict objectForKey:#"name"];
//...you get the point
}
Now you can populate your row by just setting the properties of the row. For example, if you are using the default UITableViewCell:
cell.textLabel.text = name;
There is a bit more to this that you can do for better data/model/view separation, but I have just included examples as if it were all done locally in one file.
Related
In My Notes Application I Want to Add A Option Of Task Expiry Date or Target Date for That I Save Date From UIDatePicker in Coredata, But Now How I Fetch It?? I Want to fetch It And Store It In Label..... Please Give Me Answer
This is how you can read out values from CoreData:
// context is your NSManagedObjectContext
var fetchRequest = NSFetchRequest(entityName: "YourEntity")
myData = context!.executeFetchRequest(fetchRequest, error: nil) as [YourCoreDataClass]
So in myData there is an Array of Objects - if there is only 1 object stores, check out with:
if(myData.count > 0) {
myLabel.text = myData.last!.property //(the property here for the last entry)
}
You could also you a predicate, to filter your Objects (like for a specific value)
let myPredicate = NSPredicate(format: "id = %#", anyValue)
fetchRequest.predicate = myPredicate
And read more here:
https://developer.apple.com/library/ios/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectContext_Class/index.html
I have this dictionary in objective c:
{
awayScore = 2;
awayTeam = "Kode IF";
events = (
{
eventType = "01:00";
name = "01:00";
},
{
eventType = "01:00";
name = "01:00";
}
);
homeScore = 1;
homeTeam = "Partille IF FK ";
time = "01:00";
}
Now for populating a tableview i would need to know the size of "events" items so i can return the number of rows. Also how could i iterate then through them? (now I'm thinking when I'm going to use the values to populate the cells)
so 1) How can i get the size of it
and 2) How can i iterate through them and get the different values in uitableview
I know how to iterate through ALL THE KEYS, but since i don't know how to just loop through a specific key that has many items i can't show you what i have done so far
Thanks!!
Your JSon events object should be a JSon Array, so you can fast enumerate through it.
`
NSArray *events = jsonDictonary[#"events"];
for (NSDictonary *event in events) {
//parse each event
}
Where JsonDictionary is your entire Json object.
The AddressBook Framework offers a great method for initializing an ABPerson with a vCard, by using the initWithVCardRepresentation: method.
What I want to do is update a contact with a certain vCard. I can't use initWithVCardRepresentation: because this will give me a new ABPerson object with a new uniqueId and I want to keep the uniqueId in between these changes.
What's an easy way to go about doing something like this?
Thanks!
initWithVCardRepresentation is still the slickest way to turn your vCard into an ABPerson.
Just use the results of it to find the matching person in your Address Book and then iterate over the vCard properties, placing them into the existing record. The save at the end will harden your changes.
The following example assumes that the unique "keys" will be last-name, first-name. You can modify the search element if you want to include companies where no name is listed or whatever, or you could change the iteration scheme by getting [AddressBook people], and then iterating over the people and using only those records where the key-value pairs match to your satisfaction.
- (void)initOrUpdateVCardData:(NSData*)newVCardData {
ABPerson* newVCard = [[ABPerson alloc] initWithVCardRepresentation:newVCardData];
ABSearchEleemnt* lastNameSearchElement
= [ABPerson searchElementForProperty:kABLastNameProperty
label:nil
key:nil
value:[newVCard valueForProperty:kABLastNameProperty]
comparison:kABEqualCaseInsensitive];
ABSearchEleemnt* firstNameSearchElement
= [ABPerson searchElementForProperty:kABFirstNameProperty
label:nil
key:nil
value:[newVCard valueForProperty:kABFirstNameProperty]
comparison:kABEqualCaseInsensitive];
NSArray* searchElements
= [NSArray arrayWithObjects:lastNameSearchElement, firstNameSearchElement, nil];
ABSearchElement* searchCriteria
= [ABSearchElement searchElementForConjunction:kABSearchAnd children:searchElements];
AddressBook* myAddressBook = [AddressBook sharedAddressBook];
NSArray* matchingPersons = [myAddressBook recordsMatchingSearchElement:searchCriteria];
if (matchingPersons.count == 0)
{
[myAddressBook addRecord:newVCard];
}
else if (matchingPersons.count > 1)
{
// decide how to handle error yourself here: return, or resolve conflict, or whatever
}
else
{
ABRecord* existingPerson = matchingPersons.lastObject;
for (NSString* property in [ABPerson properties]) // i.e. *all* potential properties
{
// if the property doesn't exist in the address book, value will be nil
id value = [newVCard valueForProperty:property];
if (value)
{
NSError* error;
if (![existingPerson setValue:value forProperty:property error:&error] || error)
// handle error
}
}
// newVCard with it's new unique-id will now be thrown away
}
[myAddressBook save];
}
In my iPhone app.
I am copying the one mutable array(with dictionary) to another.
It is like
resultsToDisplay = [[[NSMutableArray alloc]initWithArray:resultsPassed]mutableCopy];
2012-06-21 17:07:07.441 AllinoneCalc[3344:f803] Results To Display (
{
lbl = "Monthly EMI";
result = "75.51";
}
)
2012-06-21 17:07:08.224 AllinoneCalc[3344:f803] Results Passed (
{
lbl = "Monthly EMI";
result = "75.51";
}
)
Then I am modifying one of them .
[[resultsToDisplay objectAtIndex:i] setValue:[NSString stringWithFormat:#"%.2f",[[[resultsPassed objectAtIndex:i] valueForKey:#"result"] floatValue]] forKey:#"result"];
But what is happening that both are getting edited.
2012-06-21 17:07:08.703 AllinoneCalc[3344:f803] Results Passed (
{
lbl = "Monthly EMI";
result = "75.00";
}
)
2012-06-21 17:07:08.705 AllinoneCalc[3344:f803] Results To Display (
{
lbl = "Monthly EMI";
result = "75.00";
}
)
They both are referring to the same copy.
How to solve this. I want to modify only one array.
You are only copying the array of object pointers, not the object themself. See this article on deep copying.
an array (or mutable array) is just a list of objects, and you are modifing one of the objects referred in one of your array. the second array is still pointing to the same object, so it's normal that it changes too...
you are copying the array: meaning you're copying the list of objects, not copying all the objects in list.
I'm creating a small project where I want to post a NSMutableArray containing multiple NSDictionarys to a server. The thing is that the Array is dynamic. I don't know how many dictionaries it will contain. This is the layout of the Mutablearray:
(
{
Category = Music;
Description = "Detta \U00e4r mitt quiz!";
Difficulty = 1;
Language = Swedish;
Title = "Mitt Quiz";
},
{
QuestionNr1 = {
Question = "Vilken stad bor jag i?";
RightAnswer = Uppsala;
WrongAnswer1 = Stockholm;
WrongAnswer2 = "Ume\U00e5";
WrongAnswer3 = Visby;
};
QuestionNr2 = {
Question = "Vilken stad bor jag inte i?";
RightAnswer = Uppsala;
WrongAnswer1 = Stockholm;
WrongAnswer2 = "Ume\U00e5";
WrongAnswer3 = Visby;
};
}
)
I now want to post this to PHP/MYSQL-Server. I could do this by Splitting up the array to it's string components and concatenating a string to a URL containing all it's variables. But that wouldn't work if I'm not knowing how many Questions/Dictionarys the array will contain. Plus that it feels wrong building this LONG url for the request.
Is there any other way, using JSON for example that makes posting this structure to my php-server easy?
Thanks!
This is exactly what JSON was designed to do. See the documentation for NSJSONSerialization.