How to convert an NSString to an NSArray? - ios

I have an NSString, that when I NSLog, it looks like this:
(
Music,
Music,
"Ao Dai Fashion Show"
)
I would like to convert this to an NSArray, where array[0] = Music, array[1] = Music, and array[2] = Ao Dai Fashion Show.
I have tried to first remove the () using:
NSString *jsonString = [str stringByReplacingOccurrencesOfString:#"()" withString:#""];
However, I receive an unrecognized selector sent to instance.
How can I achieve this?
Thanks
This is the original array:
NSArray *oriArray = [dictionary objectForKey:someKey];
NSLog:
(
{
"end_time" = "21:00";
"english_event" = Music;
"english_performer" = "DJ Happee From Channel 93.3";
"start_time" = "20:00";
},
{
"end_time" = "21:00";
"english_event" = Music;
"english_performer" = "Adam Cease";
"start_time" = "20:00";
},
{
"end_time" = "21:00";
"english_event" = "Ao Dai Fashion Show";
"english_performer" = "";
"start_time" = "20:00";
}
)
Here is the code to get the new NSArray containing contents Music, Music, "Ao Dai Fashion":
NSArray *newArry = [oriArray valueForKey:#"english_event"];
However, the newArry is giving me an error when I try to access its index.

I don't think that what you're logging is actually an NSString. Please check its type because it seems like it's already an instance of NSArray. Therefore you should already be able to do what you want.

-(void)parse:(NSDictionary*)dictionary{
NSArray *oriArray = [dictionary objectForKey:someKey];
NSMutableArray *arrray=[[NSMutableArray alloc] init];
for (NSDictionary *dic in oriArray)
{
[arrray addObject:[dic objectForKey:#"english_event"]];
}
}
use this it may help you....

Sorry I din't have the reputation to comment, I just thought of asking this, did you try-
NSArray *myArray = [stringOi componentsSeparatedByString:#","];
(*where stringOi is your str)
I tried with the following sample and this works, please do try yours.
NSString *stringOi=[NSString stringWithFormat:#"(
Music,
Music,
"Ao Dai Fashion Show"
)"];
NSLog(#"%#",stringOi);
NSString *jsonString = [stringOi stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *jsonStringFinal = [jsonString stringByReplacingOccurrencesOfString:#"(" withString:#""];
NSLog(#"%#", jsonStringFinal);
NSArray *myArray = [jsonStringFinal componentsSeparatedByString:#","];
NSArray *myArray1 = [myArray objectAtIndex:0];
NSLog(#"%#",myArray1);
NSArray *myArray2 = [myArray objectAtIndex:1];
NSLog(#"%#",myArray2);
NSArray *myArray3 = [myArray objectAtIndex:2];
NSLog(#"%#",myArray3);
Alternatively instead of oriArray you can get the values in a dictionary dict and then,
NSArray *myArray1 = [dict objectForKey:#"english_event"];
NSString *Music= [myArray1 objectAtIndex:0];
Hope for the best..!

Two things:
NSArray *myArray = [myDictionary objectForKey:#"Valid Key"] does not mean that myArray is actually an Array. It just means it's a pointer to an object that you've cast as an NSArray.
You can convert any NSArray or NSDictionary to a string using [myDictionaryOrArray description].
If you don't care about taking extra steps and know that when you log out the array you get what you want/are expecting, then you can definitely get your string into an array. For example:
NSString *myString = [#[Music, Music, "Ao Dai Fashion Show"] description];
NSMutableArray *stringAsArray = [NSMutableArray arrayWithArray:[myString componentsSeparatedByString:#","]];
// this loop removes the white space before and after each word in the array
for (int i = 0; i < stringAsArray.count; i++) {
stringAsArray[i] = [stringAsArray[i] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
If you need more specific code for the longer sample you gave, I'll be happy to update my answer.

(
Music,
Music,
"Ao Dai Fashion Show"
)
this is an array not a string.
This array holds three strings in each indexes , Music, Music, Ao Dai Fashion Show

Related

IOS:Objective-C: How to combine elements of arrays

I have an array of people objects stored in Core Data and I would like to create a string made by combining two attributes of each, as in firstname and lastname.
NSArray *firstArr = [[Employees valueForKey:#"first"] allObjects];
NSArray *secondArr = [[Employees valueForKey:#"last"] allObjects];
I can create a string from one attribute such as "John,Jane" with
NSString *firststr = [firstarr componentsJoinedByString:#","];
Can anyone suggest how to make a string that has the first and last names separated by commas as in John Doe, Jane Doe? Imagine there is a method but I cannot find it.
You can do it like this
NSArray *firstArr = #[#"Rajat" , #"Rajat1", #"Raj"];
NSArray *secondArr = #[#"Test" , #"Test1", #"Test2"];
NSString * str = #"";
for (int i=0; i< (firstArr<secondArr ? firstArr.count:secondArr.count); i++) {
str = [str stringByAppendingString:[NSString stringWithFormat:#"%# %#,",firstArr[i],secondArr[i]]];
}
str = [str substringToIndex:[str length]-1];
NSLog(#"%#",str);

string handling in ios

I am getting String data from server in the format below. I want to get the value for every tag like phonenumber and name etc. I am able to convert it in array by comma separator. how to get individual values?
Company:Affiliated CO,Organization:TECHNICAL EDUCATION
SOCIETY,Organization:SINHGAD,Organization:National Basketball Association,Person:Parikshit N. Mahalle,PhoneNumber:81 98 22 416 316,PhoneNumber:9120-24100154,Position:Professor,SportsEvent:NBA.
Say your original string is stored in rawString.
You need to :
1) split the string by ,
NSArray *pieces = [rawString componentsSeparatedByString:#","];
2) for each item in this array, split it by :, and add it to a dictionary :
NSMutableDictionary *dict = [NSMutableDictionary new];
for (NSString *piece in pieces) {
NSArray *splitPiece = [piece componentsSeparatedByString:#":"];
// key is at splitPiece[0], value is at splitPiece[1]
dict[splitPiece[0]] = splitPiece[1];
}
Then you'll have a dictionary of what you wanted in the first place.
But as suggested in the comments, it would be far better (and more flexible) for you to receive JSON data.
Edit: your original string shows there are multiple fields named Organization. The code I've given is not designed to handle such cases, it's up to you to build upon it.
If this data is not being returned as a JSON object then you'll have to go with #Clyrille answer. But if it is JSON then NSJSONSerialization:JSONObjectWithData:options:error: will be the way to go.
EXAMPLE
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:/*urlResponse*/ options:0 error:nil];
NSString *company = [json objectForKey:#"Company"];
NSString *Organization = [json objectForKey:#"Organization"];
NSString *Person = [json objectForKey:#"Person"];
NSString *PhoneNumber = [json objectForKey:#"PhoneNumber"];
NSString *Position = [json objectForKey:#"Position"];
NSString *SportsEvent = [json objectForKey:#"SportsEvent"];

How to get first string of NSArray

Pretty straightforward question:
I have an array like so:
#[#"John Doe", #"Mister Appleseed", #"Steve"];
if it has two (or more) words, I want to delete them all but the first, so the output array should looke something like this:
#[#"John", #"Mister", #"Steve"];
How do I do this?
NSArray * arr = #[#"John Doe", #"Mister Appleseed", #"Steve"];
NSMutableArray * tmp = [NSMutableArray array];
for (NSString * s in arr)
{
NSArray * cmpnts = [s componentsSeparatedByString:#" "];
[tmp addObject:cmpnts[0]];
}
arr = tmp;
Check the following code:
NSMutableArray *finalArray = [[NSMutableArray alloc] init];
NSArray *sourceArray = #[#"John Doe", #"Mister Appleseed", #"Steve"];
for(NSString *str in sourceArray){
[finalArray addObject:[str componentsSepratedByString:#" "] objectAtIndex:0]];
}
You iterate over the array of names, split each at spaces (" "), and then grab the first object: the first name.
NSArray *nameArray = #[#"Name", #"Name Two"]; // original array
NSMutable *modifiedNameArray = [NSMutableArray new]; // new mutable array to add new names
for (NSString *fullName in nameArray) { // for loop
NSString *firstName = [[fullName componentsSeparatedByString:#" "] objectAtIndex:0]; // extract first name
[modifiedNameArray addObject:firstName]; // add first name to mutable array
}
You have to have two arrays, because you cannot mutate an array while it is being used in a loop (even if it's an NSMutableArray).

how to get string removing parameters [duplicate]

This question already has answers here:
Remove characters from NSString?
(6 answers)
Closed 8 years ago.
I am getting string from json dictionory but result string is in brackets, i have to get string without backets
code is
jsonDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
NSDictionary *dictResult = [jsonDictionary objectForKey:#"result"];
NSDictionary *dictPronunciations = [dictResult valueForKey:#"pronunciations"];
NSDictionary *dictAudio = [dictPronunciations valueForKey:#"audio"];
NSString *strMp3Path = [dictAudio valueForKey:#"url"];
NSLog(#"str mp3 path %#",strMp3Path);
and result is
(
(
"/v2/dictionaries/assets/ldoce/gb_pron/abate0205.mp3"
)
)
I want to get /v2/dictionaries/assets/ldoce/gb_pron/abate0205.mp3 as a string without brackets. Please help...
The object you are logging is not a NSString instance. it is a string inside an array in an array.
try:
NSLog(#"str mp3 path %#",strMp3Path[0][0]);
if this prints as desired, the object dictAudio holds with the key url is an array, with an array. you should fix that where ever you stick it into the dictionary.
Try with following code:
NSMutableArray *myArray = [dictAudio valueForKey:#"url"];
NSString *myStr = [[myArray objectAtIndex:0] objectAtIndex:0];
NSLog(#"%#", myStr);
Use this code. If your values are multiple from json then the value can be added one by one without braces :
NSMutableArray *dictPronunciations = [dictResult valueForKey:#"pronunciations"];
NSMutableArray *arrayPronunciations = [[NSMutableArray alloc] init];
for (int i = 0; i< [dictPronunciations count]; i++)
{
NSString *string = [dictPronunciations objectAtIndex:i];
NSLog(#"String = %#",string);
[arrayPronunciations addObject:string];
}
NSLog(#"Array Pronounciations = %#",arrayPronunciations);

Separate two strings from one array element

I was wondering if anyone could lend some assistance. Basically I am calling a web service and then trying to get the large hosted image url. The output from the web service is so:
images = (
{
hostedLargeUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.l.jpg";
hostedSmallUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.s.jpg";
}
);
The main problem is that the two strings are in only one of my array elements when I think they should be in 2. Also I'm not 100% but possibly they may be a dictionary :-S I'm just not sure. My code is as follows:
NSArray *imageArray = [[NSArray alloc]init];
imageArray = [self.detailedSearchYummlyRecipeResults objectForKey:#"images"];
NSLog(#"imageArray: %#", imageArray);
NSLog(#"count imageArray: %lu", (unsigned long)[imageArray count]);
NSString *hostedLargeurlString = [imageArray objectAtIndex:0];
NSLog(#"imageArrayString: %#", hostedLargeurlString);
The output (nslog's) from the above code is:
2013-04-28 18:59:52.265 CustomTableView[2635:11303] imageArray: (
{
hostedLargeUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.l.jpg";
hostedSmallUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.s.jpg";
}
)
2013-04-28 18:59:52.266 CustomTableView[2635:11303] count imageArray: 1
2013-04-28 18:59:52.266 CustomTableView[2635:11303] imageArrayString: {
hostedLargeUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.l.jpg";
hostedSmallUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.s.jpg";
}
Does anyone have any idea how I can seperate the one element into hostedlargeUrl and hostedsmallUrl respectively?
Any help you can provide is greatly appreciated!
Actually the images array contains a dictionary
images = (
{
hostedLargeUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.l.jpg";
hostedSmallUrl = "http://i.yummly.com/Crispy-roasted-chickpeas-_garbanzo-beans_-308444.s.jpg";
}
);
so :
NSDictionary *d = [self.detailedSearchYummlyRecipeResults objectForKey:#"images"][0];
NSString *largeURL = d[#"hostedLargeUrl"];
NSString *smallURL = d[#"hostedSmallUrl"];
The value of [imageArray objectAtIndex:0] is a NSDictionary. You've incorrectly specified it as a NSString. You need the following:
NSDictionary *hostedLarguerDictionary =
(NSDictionary *) [imageArray objectAtIndex:0];
and then to access the 'large url' use:
hostedLarguerDictionary[#"hostedLargeUrl"]
or, equivalently
[hostedLarguerDictionary objectForKey: #"hostedLargeUrl"];
looks like an array with in an array so
NSArray* links = [self.detailedSearchYummlyRecipeResults objectForKey:#"images"];
NSString* bigLink = [links objectAtIndex:0];
NSString* smallLink = [links objectAtIndex:1];
or it could be a dictionary
NSDictionary* links = [self.detailedSearchYummlyRecipeResults objectForKey:#"images"];
NSString* bigLink = [links objectForKey:#"hostedLargeUrl "];
NSString* smallLink = [links objectForKey:#"hostedSmallUrl "];
you can see the class of the object by printing out the class name
NSLog(#"Class Type: %#", [[self.detailedSearchYummlyRecipeResults objectForKey:#"images"] class]);

Resources