How Do You DO A Plist Array Display with iPhone? - iphone

I have looked high and low for sample Plist display code and can't seem to find any that does what I want to do. I know it can't be too hard, but I am new to Plists.
I have the following Array in a Plist and I can't seem to get the right command to display the information. Am I doing something wrong in my Plist setup? It compiles fine but no Data gets to the iPhone Simulator.
What would be the normal way of displaying the info?
I have a condition set:
If condition one
then display "+0+1"
else
display "+0+2"
*What I am hoping it to display is:
* "this is one"
* "this is two"
* "this is three"
* else display
* "555-555-1234"
* "555-555-0000"
* "555-555-5555"
MY PLIST IS AS FOLLOWS
*
Key Type Value
*Root Dictionary (2 items)
*+0+1 Array (3 items)
*Item 0 String "this is one"
*Item 1 String "this is two"
*Item 2 String "this is three"
*+0+2 Array (3 items)
*Item 0 String "555-555-1234"
*Item 1 String "555-555-0000"
*Item 2 String "555-555-5555"
*
// read property list into memory as an NSData object
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSString *errorDesc = nil;
NSPropertyListFormat format;
// convert static property list into dictionary object
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
// assign values
self.item1 = [temp objectForKey:#"name1"];
self.item2 = [NSMutableArray arrayWithArray:[temp objectForKey:#"name2"]];
// display values
bigCheese.text = disp1;
numberZero.text = [disp2 objectAtIndex:0];
numberOne.text = [disp2 objectAtIndex:1];
numberTwo.text = [disp2 objectAtIndex:2];

Once you get a dictionary get all values for that dictionary. In your case, get all values from the temp dictionary. It should return you an array containing two arrays.
NSArray *valueArray = [temp allValues];
Now you have two arrays and if you want to access "555-555-5555", do like this:
[[valuesArray objectAtIndex:1] objectAtIndex:2];
Or if you are sure that "name1" and "name2" are the keys of your dictionary you can access it this way:
[[temp objectForKey:#"name1"] objectAtIndex:2];
Once you get this info then it is up to you to decide how you want to display it. I suggest you to DEBUG and see if the dictionary and array objects are created properly first. Not sure what are those disp1 and disp2 in the sample code you posted..

Try using:
NSString *file = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:file];
NSArray *array = [dict objectForKey:#"Array"]; NSLog(#"%#", array);
It's simple, so less chances to do something wrong.

Related

NSDictionary to NSString JSON

I am trying to wrap my head around pulling a keys value from a JSON array and saving it as a String for comparison later: The following code makes my app crash when it gets to this section of code. I don't understand why.
My json array looks like so:
[{"User_Id":"CRNA000099","User_Name":"jbliz","User_Fname":"Julia"}]
My xcode:
userarray_login = [NSJSONSerialization JSONObjectWithData:dataURL options:kNilOptions error:&error];
NSDictionary* userType = [userarray_login objectForKey:#"User_Name"];
NSString *userPermission = [userType objectAtIndex:0];
if ([userPermission isEqualToString:#"jbliz"])
{
NSLog(#"I should get the avalue here: %#", userPermission);
}
I am confused between NSDictionary and NSString. Any feedback would be a
NSMutableArray *name=[[[NSMutableArray alloc] initWithArray:[userarray_login valueForKey:#"User_Name"]]retain];
// Get the only all Names into name Array from json Array
NSString *userPermission = [name objectAtIndex:0]; // get the first name from Array
if ([userPermission isEqualToString:#"jbliz"])
{
NSLog(#"I should get the avalue here: %#", userPermission);
}
Json Array : [{"User_Id":"CRNA000099","User_Name":"jbliz","User_Fname":"Julia"},{},...] an array contains Dictionaries.
for this try like,
NSArray * userarray_login = [NSJSONSerialization JSONObjectWithData:dataURL options:kNilOptions error:&error];
for (NSDictionary * dict in userarray_login) {
NSString * name = [dict objectForKey:#"User_Name"];
if ([name isEqualToString:#"jbliz"]) {
NSLog(#"Value is here: %#", name);
}
}
Your json has array of Dictionary you need to follow below steps,
//NSJSONSerialization return you array in userarray_login
userarray_login = [NSJSONSerialization JSONObjectWithData:dataURL options:kNilOptions error:&error];
//You fetch Dictionary from the array
NSDictionary* userType = [userarray_login objectAtIndex:0];
//Fetch NSString value using keyValue
NSString *userPermission = [userType objectForKey:#"User_Name"];
//String comparison
if ([userPermission isEqualToString:#"jbliz"])
{
NSLog(#"I should get the avalue here: %#", userPermission);
}
This is correct code for your stuff.

trouble in fetching object from NSDictionary

i am making dictionary with 2 array one for keys(ids that you can see in Dic) and one for values(Birth dates that you can see in Dic) my dictionary look like this
100000297621293 = "08/31/1990";
100001904155266 = "12/30/1990";
100003248631105 = "05/27/1990";
100004327360299 = "01/01/1927";
100000157646688 = "08/22/1989";
100001069796883 = "12/03/1989";
100001475514001 = "03/09/1990";
100000717474427 = "08/05/1990";
100001221367192 = "08/05/1990";
100002586744158 = "04/15/1983";
this is just sample dic not full
then after i have another array with ids and im using that array for fetching birth dates from this Dic but i get null values plz help me my code is as below
NOTE: ARRAY WHICH I AM USING FOR KEY, ALWAYS EXIST AS KEY IN DIC
NSDictionary *birthdayDictionary =
[[NSDictionary alloc] initWithObjects:_parssedArrayOfFaceBook forKeys:_parssedArrayOfFaceBookUid];
NSLog(#"asdas%#",birthdayDictionary.description);
NSMutableArray *matches = [NSMutableArray array];
for (NSString *key in _selecteduid) {
NSLog(#" see it%#",key);
NSString *selectedBirthDate = [birthdayDictionary objectForKey:key];
NSLog(#" matched%#",selectedBirthDate);
[matches addObject:selectedBirthDate];
NSLog(#" matched%#",matches);
}
Why is *selectedBirthDate an NSMutableArray? The birth dates (values) are strings! not arrays!
NSString *selectedBirthDate = [birthdayDictionary objectForKey:key];
Assuming selecteduid is a retained property and it has values in it, this code would work fine.
NSDictionary *birthdayDictionary = [NSDictionary dictionaryWithObjects:self.parssedArrayOfFaceBook
forKeys:self.parssedArrayOfFaceBookUid];
NSMutableArray *matches = [#[] mutableCopy];
for (NSString *key in self.selecteduid){
NSString *selectedBirthDate = birthdayDictionary[key];
[matches addObject:selectedBirthDate];
}

Retrieve the substring of a strings which are in array

I am new to iphone.I have an array which contains the objects like below
"04_Num/04Num001.mp3",
"04_Num/04Num002.mp3",
"04_Num/04Num003.mp3",
"04_Num/04Num004.mp3",
"04_Num/04Num005.mp3",
"04_Num/04Num006.mp3",
"04_Num/04Num007.mp3",
"04_Num/04Num008.mp3",
"04_Num/04Num009.mp3",
"04_Num/04Num010.mp3",
"04_Num/04Num011.mp3",
"04_Num/04Num012.mp3",
"04_Num/04Num013.mp3",
"04_Num/04Num014.mp3",
"04_Num/04Num015.mp3",
"04_Num/04Num016.mp3",
"04_Num/04Num017.mp3",
"04_Num/04Num018.mp3",
"04_Num/04Num019.mp3",
"04_Num/04Num020.mp3",
"04_Num/04Num021.mp3",
"04_Num/04Num022.mp3",
"04_Num/04Num023.mp3",
"04_Num/04Num024.mp3",
"04_Num/04Num025.mp3",
"04_Num/04Num026.mp3",
"04_Num/04Num027.mp3",
"04_Num/04Num028.mp3",
"04_Num/04Num029.mp3",
"04_Num/04Num030.mp3",
"04_Num/04Num031.mp3",
"04_Num/04Num032.mp3",
"04_Num/04Num033.mp3",
"04_Num/04Num034.mp3",
"04_Num/04Num035.mp3",
"04_Num/04Num036.mp3"
but here i want retrieve the strings(objects)only after the / (i.e) for example 04_Num/04Num033.mp3 in this i want only the string 04Num033.mp3.Like this for all the above and then i have to place in an array
how it is possible if any body know this please help me...
lastPathComponent is what you need. You could do it like so:
NSMutableArray *files = [[NSMutableArray alloc] initWithCapacity:0];
for (NSString *file in songs) //Where songs is the array with the paths you have provided
{
[files addObject:[file lastPathComponent]];
}
You can separate the string into two parts using NSString's
componentsSeparatedByString:
method, and use the last string component
// Let's call your array of strings as stringsArray
NSMutableArray *prefixStrings = [[NSMutableArray alloc] init];
for (NSString *str in stringsArray) {
NSArray *stringComponents = [str componentsSeparatedByString:#"/"];
if ([stringComponents count]) {
[prefixStrings addObject:[stringComponents objectAtIndex:1]];
} }

Sort array into dictionary

I have and array of many strings.
I wan't to sort them into a dictionary, so all strings starting the same letter go into one array and then the array becomes the value for a key; the key would be the letter with which all the words in it's value's array begin.
Example
Key = "A" >> Value = "array = apple, animal, alphabet, abc ..."
Key = "B" >> Value = "array = bat, ball, banana ..."
How can I do that?
Thanks a lot in advance!
NSArray *list = [NSArray arrayWithObjects:#"apple, animal, bat, ball", nil];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *word in list) {
NSString *firstLetter = [[word substringToIndex:1] uppercaseString];
NSMutableArray *letterList = [dict objectForKey:firstLetter];
if (!letterList) {
letterList = [NSMutableArray array];
[dict setObject:letterList forKey:firstLetter];
}
[letterList addObject:word];
}
NSLog(#"%#", dict);
You can achieve what you want through the following steps:
Create an empty but mutable dictionary.
Get the first character.
If a key for that character does not exist, create it.
Add the word to the value of the key (should be an NSMutableArray).
Repeat step #2 for all keys.
Here is the Objective-C code for these steps. Note that I am assuming that you want the keys to be case insensitive.
// create our dummy dataset
NSArray * wordArray = [NSArray arrayWithObjects:#"Apple",
#"Pickle", #"Monkey", #"Taco",
#"arsenal", #"punch", #"twitch",
#"mushy", nil];
// setup a dictionary
NSMutableDictionary * wordDictionary = [[NSMutableDictionary alloc] init];
for (NSString * word in wordArray) {
// remove uppercaseString if you wish to keys case sensitive.
NSString * letter = [[word substringWithRange:NSMakeRange(0, 1)] uppercaseString];
NSMutableArray * array = [wordDictionary objectForKey:letter];
if (!array) {
// the key doesn't exist, so we will create it.
[wordDictionary setObject:(array = [NSMutableArray array]) forKey:letter];
}
[array addObject:word];
}
NSLog(#"Word dictionary: %#", wordDictionary);
Take a look at this topic, they solves almost the same problem as you — filtering NSArray into a new NSArray in objective-c Let me know if it does not help so I will write for you one more code sample.
Use this to sort the contents of array in alphabetical order, further you design to the requirement
[keywordListArr sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
I just wrote this sample. It looks simple and does what you need.
NSArray *names = [NSArray arrayWithObjects:#"Anna", #"Antony", #"Jack", #"John", #"Nikita", #"Mark", #"Matthew", nil];
NSString *alphabet = #"ABCDEFGHIJKLMNOPQRSTUWXYZ";
NSMutableDictionary *sortedNames = [NSMutableDictionary dictionary];
for(int characterIndex = 0; characterIndex < 25; characterIndex++) {
NSString *alphabetCharacter = [alphabet substringWithRange:NSMakeRange(characterIndex, 1)];
NSArray *filteredNames = [names filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF BEGINSWITH[C] %#", alphabetCharacter]];
[sortedNames setObject:filteredNames forKey:alphabetCharacter];
}
//Just for testing purposes let's take a look into our sorted data
for(NSString *key in sortedNames) {
for(NSString *value in [sortedNames valueForKey:key]) {
NSLog(#"%#:%#", key, value);
}
}

How to create image and labels using location data stored in NSArray

i have to create an 2images and 3 labels by using code (cgrectmake)and i am having X location, y location, width and height all are stored in arrays(which i have retrieved from the web services)how can i create the image and labels can any one help me
You can join the elements of an array together with the NSString componentsJoinedByString class method:
NSString myString = [myNSArray componentsJoinedByString:#"x"];
where x is the characters you'd like to appear between each array element.
Edited to add
So in your newly-added code if these are the label values:
lbl = #"zero"
lbl1 = #"one"
lbl2 = #"two"
and you want to join them together with a space character then if you did this:
NSString *temp = [labelArray componentsJoinedByString:#" "];
NSLog(#"temp = %#", temp);
then this is what would be logged:
zero one two
Edited to further add
If you are instead trying to join the label values together to make xml elements then you might do something like this:
NSString *joinedElements = [labelArray componentsJoinedByString:#"</label><label>"];
NSString *temp = [NSString stringWithFormat:#"<label>%#</label>", joinedElements];
NSLog(#"temp = %#", temp);
then this is what would be logged:
<label>zero</label><label>one</label><label>two</label>
may be this is usefull to you.
NSString *str;
str = [arrayName objectAtIndex:i(Index NO)];
OK by this easily you can access object from the array. any type of object u can fetch this way only reception object type are change in left side.
Best of Luck.
Most objects have a -description method which returns a string representation of the object:
- (NSString *)description;
For example:
NSArray *array = [NSArray arrayWithObjects:#"The", #"quick", #"brown", #"fox", nil];
NSLog(#"%#", array); // prints the contents of the array out to the console.
NSString *arrayDescription = [array description]; // a string
It would help to know what you want to do with the string (how will you use the string). Also, what kind of objects do you have in the array?
In that case, Matthew's answer is one possibility. Another might be to use an NSMutableString and append the individual items, if you need control over how the string is created:
NSMutableString *string = [NSMutableString string];
if ([array count] >= 3) {
[string appendString:[array objectAtIndex:0]];
[string appendFormat:#"blah some filler text %#", [array objectAtIndex:1]];
[string appendString:[array objectAtIndex:2]];
}