Which is the best way to create NSString from an int? - cocoa-touch

Suppose I've this, int yo = 5;.
Now I want to convert that to an NSString. Here are the possible ways,
1) NSString *h = [NSString stringWithFormat:#"%d",yo];
2) NSString *k = #(yo).stringValue;
3) NSString *s = [NSNumber numberWithInt:yo].stringValue;
4) any other "best" ways?
Which one is the best and why?

The first way is better because it avoids having to create an intermediate instance of NSNumber. Also note that
#(5).stringValue;
and
[#(5) discriptionWithLocale:nil];
are equivalent statements.

Related

NSDictionary into NSString conversion issue

What is the problem with this piece of code?
That works:
NSDictionary* fact = [facts objectAtIndex:currentFactId];
[myTextView setText:[fact objectForKey:#"fact"]];
That doesn't work:
NSDictionary* fact = [facts objectAtIndex:currentFactId];
NSString *fact_string = [fact objectForKey:#"fact"];
That should work but still try this
NSString *fact_string = [NSString stringWithFormat:#"%#",[fact objectForKey:#"fact"]];
Think that the objectForKey doesn't ensures you that will be returning an NSString. Since you are assigning its value you'll need to encapsulate it like Neo said. I wouldn't do the set and the assigning without that encapsulating or, at least, a casting to (NSString *).

NSString takes substrings

I have the following NSString in objective C:
[["123"], ["456"], ["adg"]]
and I would like to separate into differents strings like this :
aux = 123;
aux2 = 456;
aux3 = adg;
Please, anyone can help me
Thanks
you can call
NSArray *arrayOfSubStrings = [myString componentsSeparatedByString:#","];
then loop through for each string in the array and remove the square brackets by calling
aux = [stringByReplacingOccurrencesOfString:[arrayOfSubStrings ObjectAtIndex:x] withString:#""]
See NSString Doc for more details
NSString *str = #"[[\"123\"], [\"456\"], [\"adg\"]]";
NSString *new = [[str substringFromIndex:4]substringToIndex:7];
new will be 123
and so on
If you have control over the string format that you're parsing I'd highly recommend looking at JSON and using NSJSONSerialization to parse it. This is more preferable than re-inventing the wheel by defining your own format to store primitive objects.

How to append NSString wiht number?

I'm new in Cocoa.
I have NSString - (e.g) MUSIC . I want to add some new NSString in Array,
And want to check something like this
if MUSIC already contained in Array, add Music_1 , after Music_2 and so on.
So I need to be able read that integer from NSString, and append it +1 .
Thanks
Use
NSString *newString = [myString stringByAppendingString:[NSString stringWithFormat:#"_%i", myInteger]];
if myString is "music", newString will be "music_1" or whatever myInteger is.
EDIT: I seem to have gotten the opposite meaning from the other answer provided. Can you maybe clarify what it is you are asking exactly?
Check it out:
NSMutableArray *array = [NSMutableArray arrayWithObjects:#"123", #"qqq", nil];
NSString *myString = #"MUSIC";
NSInteger counter = 0;
if ([array containsObject:myString]){
NSString *newString = [NSString stringWithFormat:#"%#_%d", myString, ++counter];
[array addObject:newString];
}
else
[array addObject:myString];
For checking duplicate element in Array you can use -containsObject: method.
[myArray containsObject:myobject];
If you have very big array keep an NSMutableSet alongside the array.Check the set for the existence of the item before adding to the array. If it's already in the set, don't add it. If not, add it to both.
If you want unique objects and don't care about insertion order, then don't use the array at all, just use the Set. NSMutableSet is a more efficient container.
For reading integer from NSString you can use intValue method.
[myString intValue];
For appending string with number you can use - (NSString *)stringByAppendingString:(NSString *)aString or - (NSString *)stringByAppendingFormat:(NSString *)format ... method.
Here's how you convert a string to an int
NSString *myStringContainingInt = #"5";
int myInt = [myStringContainingInt intValue];
myInt += 1;
// So on...

Converting NSString to key value pair

I have a response from server which is NSString and looks like this
resp=handshake&clientid=47D3B27C048031D1&success=true&version=1.0
I want to convert it to key value pair , something like dictionary or in an array .
I couldn't find any useful built-in function for decoding the NSString to NSdictionary and replacing the & with space didn't solve my problem , can anyone give me any idea or is there any function for this problem ?
This should work (off the top of my head):
NSMutableDictionary *pairs = [NSMutableDictionary dictionary];
for (NSString *pairString in [str componentsSeparatedByString:#"&"]) {
NSArray *pair = [pairString componentsSeparatedByString:#"="];
if ([pair count] != 2)
continue;
[pairs setObject:[pair objectAtIndex:1] forKey:[pair objectAtIndex:0]];
}
or you could use an NSScanner, though for something as short as a query string the extra couple of arrays won't make a performance difference.

Split an NSString to access one particular piece

I have a string like this: #"10/04/2011" and I want to save only the "10" in another string. How can I do that?
NSArray* foo = [#"10/04/2011" componentsSeparatedByString: #"/"];
NSString* firstBit = [foo objectAtIndex: 0];
Update 7/3/2018:
Now that the question has acquired a Swift tag, I should add the Swift way of doing this. It's pretty much as simple:
let substrings = "10/04/2011".split(separator: "/")
let firstBit = substrings[0]
Although note that it gives you an array of Substring. If you need to convert these back to ordinary strings, use map
let strings = "10/04/2011".split(separator: "/").map{ String($0) }
let firstBit = strings[0]
or
let firstBit = String(substrings[0])
Either of these 2:
NSString *subString = [dateString subStringWithRange:NSMakeRange(0,2)];
NSString *subString = [[dateString componentsSeparatedByString:#"/"] objectAtIndex:0];
Though keep in mind that sometimes a date string is not formatted properly and a day ( or a month for that matter ) is shown as 8, rather than 08 so the first one might be the worst of the 2 solutions.
The latter should be put into a separate array so you can actually check for the length of the thing returned, so you do not get any exceptions thrown in the case of a corrupt or invalid date string from whatever source you have.
Its working fine
NSString *dateString = #"10/10/2010";//Date
NSArray* dateArray = [dateString componentsSeparatedByString: #"/"];
NSString* dayString = [dateArray objectAtIndex: 0];
Objective-c:
NSString *day = [#"10/04/2011" componentsSeparatedByString:#"/"][0];
Swift:
var day: String = "10/04/2011".componentsSeparatedByString("/")[0]
Use [myString componentsSeparatedByString:#"/"]
I have formatted the nice solution provided by JeremyP above into a more generic reusable function below:
///Return an ARRAY containing the exploded chunk of strings
+(NSArray*)explodeString:(NSString*)stringToBeExploded WithDelimiter:(NSString*)delimiter
{
return [stringToBeExploded componentsSeparatedByString: delimiter];
}
Swift 3.0 version
let arr = yourString.components(separatedBy: "/")
let month = arr[0]