IOS - ObjC - JSONString From NSString - objective-c

I need to create a JsonString from a NSString, without any key in ObjC.
All tutorials talks about serialization from NSDictionary or NSData.
My string is like #"fr-FR".
The result i'm looking for is like #"{"fr-FR"}", but dynamically.
Can't do it myself because i will need to do the same stuff for different kind of arguments.
Thanks in advance :)

To achieve the result you are asking for (even if it's not a proper JSON) you could try something like this:
NSString *myString = #"fr-FR"; // Or whatever
NSString *result = [NSString stringWithFormat:#"{\"%#\"}", myString];

You need to use a JSON framework/library, for example TouchJSON, and then you can do the following to encode your NSString:
theData = [[CJSONSerializer serializer] serializeObject:theString
error:&theError];
(from the demo code here).

You could use NSJSONSerialization class if you develop on IOS 5 +
create data with your string
NSString *myString = #"fr-FR"; // Or whatever
NSString *result = [NSString stringWithFormat:#"{%#}", myString];
NSData* data=[result dataUsingEncoding:NSUTF8StringEncoding];
and then use
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error
to create your JSON object
(just typed, not tested)

IMHO after reading the json spec again ( http://www.json.org ) {"string"} isn't valid json and the code you are using in c# produces invalid results. However, if you need to communicate with c# code that acts this way you should just encode the string itself using a JSON library and then afterwards pack it in curly braces. That way you get all the escaping needed for JSON for special cases (e.g. quotes and whatnot) which you don't if you just add quotes and braces manually.

Related

EXC_BAD_ACCESS while filling in the dictionary (?)

void CountlyRecordEventSegmentationCountSum(const char * key, const char * segmentation, int count, double sum)
{
NSString * seg = CreateNSString(segmentation);
NSArray * entries = [seg componentsSeparatedByString:#"`"];
NSDictionary * dict = [NSDictionary dictionary];
for (id entry in entries)
{
NSArray * keyValue = [entry componentsSeparatedByString:#"|"];
[dict setValue:[keyValue objectAtIndex:1] forKey:[keyValue objectAtIndex:0]];
}
[[Countly sharedInstance] recordEvent:CreateNSString(key) segmentation:dict count:count sum:sum];
}
I put "?" in the title because I'm not entirely sure if the problem is in the code above but that's my best guess. I'm integrating Countly iOS plugin with Unity and one of Countly plugin's methods take NSDictionary * as argument. As I don't know how to send a dictionary from C# to Objective-C I'm storing my dict in a string, sending it to Objective-C and then recreating the dictionary (the code above).
But that's probably even not relevant. I know EXC_BAD_ACCESS usually has something to do with unfreed resources or sth so maybe you can see what I'm doing wrong (I don't know Objective-C at all, just writing a few lines needed by the plugin).
Edit:
From Unity sample:
// Converts C style string to NSString
NSString * CreateNSString (const char * string)
{
if (string)
return [NSString stringWithUTF8String: string];
else
return [NSString stringWithUTF8String: ""];
}
The error you've made is that you are trying to modify immutable version of NSDictionary.
One cannot modify contents of the NSDictionary after it's initialization. You should use NSMutableDictionary instead.
Here is a documentation on NSMutableDictionary.
And here is an example of how to create mutable version of an immutable object that conforms to NSMutableCopying protocol.
You need to be using NSMutableDictionary, you can't modify an NSDictionary.
Also, you should use setObject:forKey: because setValue:forKey: is a KVC method. It happens to do the same thing on an NSMutableDictionary for most keys, but it is marginally slower.
Finally, you should check that [keyValue count] >= 2 before trying to access the objects at indexes 0 and 1.
Edit Also, CreateNSString() looks suspicious. It might be either leaking or prematurely releasing the string. But you need to post the code. In any case, I'd use
seg = [NSString stringWithUTF8String: segment];
or, other appropriate method if segment is not encoded in UTF-8.

What is an actual example of the difference between NSString to NSMutablestring could look like?

I'v been looking around in the questions here and could not find simple example to point me the difference while I was testing some code of my own to test the differentiation.
From what I understand, in an "immutable" string such as 'NSString', I could not preform any 'NSString' methods to modify the string, such as:
NSString *s = #"cat";
s = [NSString stringWithString:#"blamp"];
NSLog(#"%#", s);
But it does work..
Please try to give me and other newbies out there a very simple example of what won't work and why.
tnx
The statement :
s = [NSString stringWithString:#"blamp"];
actually creates a new memory location for the string "blamp" and the old address of s gets replaced by this new address.
And you get the feel that the same s is updated!!! Actually the pointer now points to some other memory addresss.
String manipulation means changing the same string : as if you try
NSString *s = #"cat";
[s appendString:#"s"];//tries to append to the same. this will through error.
//the above works with NSMutableString.

Understanding Instantiation in Objective-C

I’m currently trying to learn Objective-C by reading books and online tutorials, also referring to the Apple documentation but some things just don’t click. I have a question about classes, I have been using the NSString for a while now without putting too much attention on how it is used.
I was under the impression that in order for someone to be able to use a method from a certain class in Objective-C you first needed to instantiate it, something like…
ClasssName *varName = [[ClassName alloc]init];
Then you would call methods like...
[varName someMethod];
But looking at how the NSString is used I’m now I little confused, for instance here is how we would normally use it...
NSString *someString = #"some text here";
[someString stringByAppendingFormat: #"some text = %d", 3];
Following what I have read about classes we would need to do something like the following instead.
NSString *someString = [[NSString alloc]initWithString: #"some text here"];
[someString stringByAppendingFormat: #"some text = %d", 3];
Can someone explain why some classes do not require instantiation before using its methods?
Objective-C knows some abbreviations that are called literals. The compiler is aware of the special notation. A string literal is compiled into the binary and exits throughout the lifetime of an app.
For most cases it will behave like an object created on runtime.
if two literals are identical, only one object will be created and live forever
if you create NSString *string = [[NSString alloc] initWithString:#"My String"]; with #"My String" being used as a literal before, also string can point to it.
Since Apple LLVM Compiler 4.0 Objective-C knows some more literals. But in contrast to string literals these literals are created during runtime through convenient initializers.
Note that
[someString stringByAppendingFormat: #"some text = %d", 3];
does not change someString. It returns a new string object.
NSString *newString = [someString stringByAppendingFormat: #"some text = %d", 3];
The #"Text" syntax gives you an autoreleased string back, it can be thought of as a shorthand.
when you write
[[NSString alloc]initWithString: #”some text here”];
you conceptually create an autoreleased string with #”some text here” and then you create a retained new string with initWithString.

How do I convert HTML NSData to an NSString?

I'm using [NSData dataWithContentsOfURL:] to create two NSData instances and I want to compare these instances to gauge how different they are. Since they're both from the same website, using a string to find what is different will help me highlight the actual element(s) that has (have) changed. Is it possible to change this data to a string to find the difference?
Try initWithData:encoding: method of NSString to create string with your data.
Exmp: NSString *str = [[NSString alloc] initWithData:someData encoding:NSUTF8StringEncoding]
Why don't you use NSString
stringWithContentsOfURL:encoding:error:

Is there a method for adding one NSString for NSData?

I'm working on writing to a file one user input on a textField.
So far I have one NSFileManager which writes data to a file. Still, I have no way of putting the textField input inside a file.
Is there a way do add a string value to NSData so I can write it?
you can get NSData from NSString,
NSData *newData = [yourString dataUsingEncoding:NSUTF16StringEncoding];
use encoding that fits your case.
append the obtained data to existing NSData,
[existingData appendData:newData]
Note: "existingData" should be an instance of NSMutableData.
Use below code as your reference.
NSString* myString = #"Is there a method for adding one NSString for NSData";
NSData* myData= [myString dataUsingEncoding:NSUTF8StringEncoding];