ReConvert NSString to NSArray - objective-c

I have converted an NSArray to NSString using below code
Suppose i have an array with some data in it.
NSString *sample=[array description];
NSLog(#"%#",sample);
which prints:
(
{
URL = "1a516af1a1c6020260a876231955e576202bbe03.jpg##37911944cc1ea8fd132ee9421a7b3af326afcc19.jpg";
userId = 0;
wallpaperId = 31;
},
{
URL = "a9356863fa43bc3439487198283321622f88e31f.jpg##f09c743ebdc26bb9f98655310a0529b65a472428.jpg";
userId = 0;
wallpaperId = 30;
}
)
It looks like array but it is actually a string.
Now I am wondering, how can I reconvert back to NSArray?
Help appreciated.
And please this not a duplicate question, I couldn't found the same anywhere on SO.

You cannot rely on the results of description as it is not a convert to string operator, but merely a debugging aid. There is nothing to stop it changing between O/S releases and there is no equivalent fromDescription method.
The conventional way of serializing an Objective-C collection to and from a string is to use JSON, so look at the NSJSONSerialization class.

the
NSString componentsseparatedbystring
method will return an array of components separated by a string

Related

Converting string to static constant

I have in my objective-c application a number of constants that I need to have inputted from an external source using strings. The reason of course, is that constants are better to work with, but can't be passed external.
I have made this objective-c code to convert, and it works 100%, but a) it is ugly, and b) quite obscure. I suppose I could have converted to NSNumber and made an array, but that seems like a lot of code/processing (though maybe the right solution)
Can anyone provide a better solution?
NSArray *types = #[#"text_input",#"textbox",#"select",#"yesno",#"date",#"signature",#"label",#"SectionHeading"];
int indexes[10];
indexes[0] = FieldTypeTextInput;
indexes[1] = FieldTypeTextBox;
indexes[2] = FieldTypeSelect;
indexes[3] = FieldTypeYesNo;
indexes[4] = FieldTypeDate;
indexes[5] = FieldTypeSignature;
indexes[6] = FieldTypeLabel;
indexes[7] = FieldTypeSectionHeading;
for (int i=0;i<[types count];i++)
{
NSString *string_i = [types objectAtIndex:i];
if ([type_string isEqualToString:string_i])
I suggest to use an NSDictionary.
enum YourNiceTypes : NSInteger {FieldNotFound, FieldTypeTextInput, FieldTypeTextBox, ...};
NSDictionary *types = #{"text_input" : #(FieldTypeTextInput), ... };
enum YourNiceType type = [types[textInput] integerValue];
You used the trick to define wrong input with zero, which will be handled automatically correctly, as calling integerValue on a nil object will return 0.

Comparing a string in a NSMutableArray to a NSString

I'm very new to objective-c and this question may seem very simple so I am sorry if it is. I think I know how to get a user to input a string in C and comparing that to a string in an array by using strcmp. For instance (not sure if code is right as I'm not very good at c either)
char *arr[2];
arr[0] = "hello";
arr[1] = "goodbye";
char myString[10];
printf("enter greeting\n");
scanf("%s",myString);
if(strcmp(myString,arr[0]) == 0 )
{
printf("hello to you to");
}
if(strcmp(myString,arr[1]) == 0 )
{
printf("goodbye then");
}
But I'm trying to do the same thing with NSMutableArrays and NSStrings. So far it goes:
NSMutableArray *myStringArray = [[NSMutableArray alloc] init];
[myStringArray addObject:#"hello"];
[myStringArray addObject:#"goodbye"];
char greetingStr[40];
printf("enter greeting\n");
scanf("%s", greetingStr);
NSString *greeting = [NSString stringWithUTF8String:greetingStr];
//Some method to compare the strings
I was wondering what the code is the compare NSString with objects in NSMutableArrays. Sorry if it was badly explained but I am very new to programming and please keep any answers quite simple as I'm still very new to this. Thank you in advance.
"Some method to compare the strings" is:
isEqualToString:, if you're only interested in equality of strings;
compare:, if you also want to get information about their lexicographical ordering.

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.

replace characters in NSString

I would like to wipe a NSString object in my code (replace every characters by 0).
To do that I tried this :
NSString *myString;
for (int i=0; i<[myString length]; i++)
{
myString[i] = 0;
}
But it doesn't compile : "Incompatible types in assignment" at line myString[i] = 0;
I understand, but I can't use function stringByReplacingOccurancesOfString because it creates a new object and I would like to replace characters in my first object.
Any help ?
NSString is immutable, meaning that you can not change its contents once its created. You have NSMutableString for that purpose.
Also, you can not access the characters in a NSString or NSMutableString with this syntax:
myString[i] = 0;
NSStrings and NSMutableStrings are objects and you work with objects by sending messages to them. For instance, you have characterAtIndex: method that returns the character at the given index, or NSMutableString's replaceOccurrencesOfString:withString:options:range: that replaces all occurrences of a given string in a given range with another given string.
By Definition, NSString is an immutable class, so the data inside of it is unchangeable.
You are looking for the NSMutableString class, which implements the following method:
replaceOccurrencesOfString:withString:options:range:
Which you can use to replace characters or substrings within the object you send that message to.

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]