xcode split NSString to other NSStrings - xcode

{"Title":"Chatroom","Year":"2010","Rated":"R","Released":"11 Aug 2010","Genre":"Drama, Thriller","Director":"Hideo Nakata","Writer":"Enda Walsh, Enda Walsh","Actors":"Aaron Johnson, Imogen Poots, Matthew Beard, Hannah Murray","Plot":"A group of teenagers encourage each other's bad behavior.","Poster":"http://ia.media-imdb.com/images/M/MV5BMjE0MjM5MDM2MF5BMl5BanBnXkFtZTcwMzg1MzY0Mw##._V1._SX320.jpg","Runtime":"1 hr 37 mins","Rating":"5.3","Votes":"1000","ID":"tt1319704","Response":"True"}
i get this data with nsstring and my question is how to split data that , separates to another nsstrings, but i want to make as commas so much nsstrings

Use the following
NSString *str; //Pass your string to str
NSArray *array = [str componentsSeparatedByString:#","];
for(int i = 0; i < [array count]; i++) {
// Here just take strings one by one
}

NSString *string= //pass the string whatever you want.
NSArray *splitArray = [string componentsSeparatedByString:#","]; //it separates the string and store it in the different different indexes.
Ex:
NSString *str= #"one,two,three";
NSArray *array = [str componentsSeparatedByString:#","]; //it separates the string and store it in the different different indexes(one is at index 0 ,two is at index 1 and three is at index 2).

Related

NSString to NSArray and iterate

I have a code that creates an NSString and separates value with a comma. What I need to do is take that string, convert it to a NSArray and separate each value from the NSString between the commas, then iterate through each one. The code below returns the array as a single string
NSString *emails = #"testemail#gmail.com, testemail2#gmail.com";
NSArray *listItems = [emails componentsSeparatedByString:#", "];
for (int i = 0; i < [listItems count]; i++) {
NSString *address = (NSString*) [listItems objectAtIndex:i];
NSLog (#"ADDRESS: %#", address);
The Log shows the response testemail#gmail.com, testemail2#gmail.com when I want it to separate each one individually. Should this be an NSMutableArray instead?
The code is correct. You'll get two (separate) lines starting with ADDRESS:
But nowadays (actually since 2009!) it's highly recommended to use Fast Enumeration if the loop index is not needed
NSString *emails = #"testemail#gmail.com, testemail2#gmail.com";
NSArray *listItems = [emails componentsSeparatedByString:#", "];
for (NSString *email in listItems) {
NSLog(#"ADDRESS: %#", email);
}

How to use "valueforkey"?

I'm trying to do the following - I have an Array in which some strings are stored. These strings shall be used to call an NSArray. An example will clarify what I'm trying to do:
This is the working code that I'm trying to achieve ("briefing0" is of type NSArray):
NSString *path = [docsDir stringByAppendingPathComponent:[briefing0 objectAtIndex:indexPath.row]];
This is the "same" code that I'm trying to use:
int i = 0;
NSString *path = [docsDir stringByAppendingPathComponent:[(NSArray *)[NSString stringWithFormat:#"briefing%d", i] objectAtIndex:indexPath.row]];
Any ideas?
Thanks in advance!
Tom
Assuming that briefing0 is actually a property, then yes, this is possible (and not uncommon) in ObjC via KVC.
int i = 0;
NSString *prop = [NSString stringWithFormat:#"briefing%d", i];
NSArray *array = [self valueForKey:prop];
NSString *value = [array objectAtIndex:indexPath.row];
... etc. ...
-valueForKey: is the piece you're looking for. Note that this will throw an exception if you construct a key that does not exist, and so must be used with extreme care.

NSArray Sorting

I have an NSArray with values that I am pulling from an NSDictionary using a selector to sort with which has the following values:
John
Brian
Alex
....
Dave
When I use the code below, since they are being compared as strings, the list comes back with:
NSArray *array = [[[self myDictionary] allValues] sortedArrayUsingSelector:#selector(compare:)];
John
Dave
Brian
...
How can I get these values to sort correctly where they are in order 1, 2, 3, etc.? I've looked at several different examples for sorting, but have not been able to find an example like mine. I must also mention that I'm new to objective-c and iOS. Any help would be greatly appreciated.
Thanks!
I was actually able to figure out the solution. I created an NSComparisonResult block using custom logic to read the number portion off of the front of each string and then comparing them numerically:
NSComparisonResult (^sortByNumber)(id, id) = ^(id obj1, id obj2)
{
//Convert items to strings
NSString *s1 = (NSString *)obj1;
NSString *s2 = (NSString *)obj2;
//Find the period and grab the number
NSUInteger periodLoc1 = [s1 rangeOfString:#"."].location;
NSString *number1 = [s1 substringWithRange:NSMakeRange(0, periodLoc1)];
NSUInteger periodLoc2 = [s2 rangeOfString:#"."].location;
NSString *number2 = [s2 substringWithRange:NSMakeRange(0, periodLoc2)];
//Compare the numeric values of the numbers
return [number1 compare:number2 options:NSNumericSearch];
};
Then I sort my array by calling:
NSArray *array = [[[self myDictionary] allValues] sortedArrayUsingComparator:sortByNumber];

Check for String within a String

I'm trying to compare two strings
NSString strOne = #"Cat, Dog, Cow";
NSString strTwo = #"Cow";
How do I determine if strOne contains strTwo
Try using rangeOfString:
NSRange result = [strOne rangeOfString:strTwo];
From the documentation:
Returns an NSRange structure giving the location and length in the receiver of the first occurrence of aString. Returns {NSNotFound, 0} if aString is not found or is empty (#"").
For anyone needing the code to check is a string exists within a string, here's my code thanks to fbrereto. This example checks to see if any string contained in an array of strings (stringArray) can be found within a string (myString):
int count = [stringArray count];
for (NSUInteger x = 0; x < count; ++x) {
NSRange range = [self.myString rangeOfString:[stringArray objectAtIndex:x]];
if (range.length > 0) {
// A match has been found
NSLog(#"string match: %#",[stringArray objectAtIndex:x]);
}
}
I believe this is the correct syntax for checking if the range exists (correcting response from Kendall):
range.location != NSNotFound
Gradually straying off topic, but I always explode my strings, which would mean just exploding it using your search string as a key and you can use the array count to see how many instances you have.
Just incase anyone is coming from a code language that uses "explode" to blow a string up into an array like me, I found writing my own explode function tremendously helpful, those not using "explode" are missing out:
- (NSMutableArray *) explodeString : (NSString *)myString key:(NSString*) myKey
{
NSMutableArray *myArray = [[NSMutableArray alloc] init];
NSRange nextBreak = [myString rangeOfString:myKey];
while(nextBreak.location != NSNotFound)
{
[myArray addObject: [myString substringToIndex:nextBreak.location]];
myString = [myString substringFromIndex:nextBreak.location + nextBreak.length];
nextBreak = [myString rangeOfString:myKey];
}
if(myString.length > 0)
[myArray addObject:myString];
return myArray;
}
works like this:
[self explodeString: #"John Smith|Age: 37|Account Balance: $75.00" key:#"|"];
which will return this array:
[#"John Smith", #"Age: 37", #"Account Balance: $75.00"];
This lets you quickly pull out a specific value in a tight space, Like if you have a client and you want to know how much money he has:
[[self explodeString: clientData key: pipe] objectAtIndex: 1];
or if you wanted specifically the dollar amount as a float:
[[[self explodeString: [[self explodeString: clientData key: pipe] objectAtIndex: 1] key: #": "] objectAtIndex: 2] floatValue];
anyway I find arrays way easier to work with and more flexible, so this is very helpful to me. Additionally with a little effort you could make an "explodable string" data type for your private library that lets you treat it like a string or return an index value based on the key
ExplodableString *myExplodableString;
myExplodableString.string = #"This is an explodable|string";
NSString *secondValue = [myExplodableString useKey: #"|" toGetValue: index];

Search a string with nsmutablearray contents

This is probably a quick and easy question, but how would I be able to search a string with the contents of a nsmutablearray which are strings. So I have the NSString *blah = #"djfald.ji". I have the nsmutablearray filled with different extensions and I want to search the string blah to see if any of the extensions have a match. I used to use -[NSRange rangeOfString:] but that doesn't work with arrays.
Thanks,
Kevin
If you really are dealing with path extensions, it's probably better to approach this the other way round. Something like:
NSString *extension = [#"djfald.ji" pathExtension];
BOOL found = [extensions containsObject:extension];
Simply use a block:
NSUInteger extIndex = [extensionArray indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
return [blah hasSuffix:obj];
}];
NSString *extension = extensionIndex == NSNotFound ? [extensionArray objectAtIndex extIndex] : nil;
Or simply loop through the array with an enumeration.

Resources