How to convert a NSObject from NSDictionary into NSString? - iphone

NSObject *url = [item objectForKey:#"link"];
This is a NSObject from NSDictionary "item". I need to convert NSObject to NSString.
Because I should use url to string.
How can I do that?
Thank you for replying.

Max has the correct casting syntax, but to be safe you'll want to do some kind of instance check at runtime, since it's not possible at compile-time in Objective-C to ensure that the type of an object in an array or dictionary is what you're expecting:
NSObject *obj = [item objectForKey:#"link"];
if ([obj isKindOfClass:[NSString class]]) {
NSString *stringValue = (NSString *)obj;
// Do something with the NSString
} else {
// You can alternatively raise an NSException here.
NSLog(#"Serious error, we expected %# to be an NSString!", obj);
}

NSString *url = (NSString*)[item objectForKey:#"link"];

Related

clean way to add query string to NSString?

So I have a NSString with a url like this:
NSString stringWithFormat:#"/reading.php?title=blah&description="blah"&image_url=blah... "
what is the best way to append query string to this string? is there a dictionary kind of way to do this?
What you want to do is this.
[NSString stringWithFormat:#"/reading.php?title=blah&description=%#&image_url=blah... ",blah];
Basically %# in the context meaning that you'll pass use a dynamic value which will be a string.
How about a category?
This is not great but for a first pass should give you something to get started
#interface NSDictionary (ps_additions)
- (NSString *)ps_URLParamsValue;
#end
#implementation NSDictionary (ps_additions)
- (NSString *)ps_URLParamsValue;
{
NSMutableString *params = [NSMutableString string];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){
[params appendFormat:#"%#=%#&", key, obj];
}];
return [params copy];
}
#end
This would end up with something like:
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:#"42", #"special_number", #"value", #"another", nil];
NSString *myString = [NSString stringWithFormat:#"/reading.php?%#", [params URLParamsValue]];
NSLog(#"%#", myString);
#=> 2012-03-20 23:54:55.855 Untitled[39469:707] /reading.php?another=value&special_number=42&
You can use something like:
NSString *parameter1 = #"blah";
NSString *parameter2 = #"anotherblah";
NSString *fullURL = [NSString stringWithFormat:#"/reading.php?title=%#&image_url=%#", parameter1, parameter2];
You can add as many parameters as you want. Use "%#" where you will be dynamically adding the text.
Good luck :)
Copy pasting from Paul.s - which is the correct answer, imo - and fixing a (most likely inconsequential) problem of a dangling ampersand...
#interface NSDictionary (ps_additions)
- (NSString *)ps_URLParamsValue;
#end
#implementation NSDictionary (ps_additions)
- (NSString *)ps_URLParamsValue;
{
if (!self.count) return #"";
NSMutableString *params = [NSMutableString string];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){
[params appendFormat:#"%#=%#&", key, obj];
}];
// return everything except that last ampersand
return [[params copy] substringToIndex:[params length]-1];
}
#end

Convert an object into Json using SBJson or other JSON library

I need a easy to use library whit examples for converting NSObjects to JSON and back again, I found a ton of parseing examples on the net for parsing JSon but not too much on converting NSObject to JSON using SBJSON, Anybody body have a good tutorial or a sample code to convert NSObject to JSON ?
With SBJSON, it's really simple.
NSString *myDictInJSON = [myDict JSONRepresentation];
NSString *myArrayInJSON = [myArray JSONRepresentation];
Of course, to go the other way array, do:
NSDictionary *myDict = [myDictInJSON JSONValue];
NSArray *myArray = [myArrayInJSON JSONValue];
Using SBJson, to convert a object to JSON string, you have to override the proxyForJson method. Like the following,
The .h file,
#interface MyCustomObject : NSObject {
NSString *receiverFirstName;
NSString *receiverMiddleInitial;
NSString *receiverLastName;
NSString *receiverLastName2;
}
#property (nonatomic, retain) NSString *receiverFirstName;
#property (nonatomic, retain) NSString *receiverMiddleInitial;
#property (nonatomic, retain) NSString *receiverLastName;
#property (nonatomic, retain) NSString *receiverLastName2;
- (id) proxyForJson;
- (int) parseResponse :(NSDictionary *) receivedObjects;
}
In the implementation file,
- (id) proxyForJson {
return [NSDictionary dictionaryWithObjectsAndKeys:
receiverFirstName, #"ReceiverFirstName",
receiverMiddleInitial, #"ReceiverMiddleInitial",
receiverLastName, #"ReceiverLastName",
receiverLastName2, #"ReceiverLastName2",
nil ];
}
And to get the object from the JSON string you have to write a parseResponse method like this,
- (int) parseResponse :(NSDictionary *) receivedObjects {
self.receiverFirstName = (NSString *) [receivedObjects objectForKey:#"ReceiverFirstName"];
self.receiverLastName = (NSString *) [receivedObjects objectForKey:#"ReceiverLastName"];
/* middleInitial and lastname2 are not required field. So server may return null value which
eventually JSON parser return NSNull. Which is unrecognizable by most of the UI and functions.
So, convert it to empty string. */
NSString *middleName = (NSString *) [receivedObjects objectForKey:#"ReceiverMiddleInitial"];
if ((NSNull *) middleName == [NSNull null]) {
self.receiverMiddleInitial = #"";
} else {
self.receiverMiddleInitial = middleName;
}
NSString *lastName2 = (NSString *) [receivedObjects objectForKey:#"ReceiverLastName2"];
if ((NSNull *) lastName2 == [NSNull null]) {
self.receiverLastName2 = #"";
} else {
self.receiverLastName2 = lastName2;
}
return 0;
}
From JSON String to Objects:
SBJsonParser *parser = [[SBJsonParser alloc] init];
// gives array as output
id objectArray = [parser objectWithString:#"[1,2,3]"];
// gives dictionary as output
id objectDictionary = [parser objectWithString:#"{\"name\":\"xyz\",\"email\":\"xyz#email.com\"}"];
From Objects to JSON String:
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
id *objectArray = [NSArray arrayWithObjects:#"Hello",#"World", nil];
// Pass an Array or Dictionary object.
id *jsonString = [writer stringWithObject:objectArray];

iOS -- get pointer from NSString containing address

If I have a pointer to an object foo with address (say) 0x809b5c0, I can turn that into an NSString by calling
NSString* fooString = [NSString stringWithFormat: #"%p", foo].
This will give me the NSString #"0x809b5c0".
What is the easiest way to reverse the process? That is, start with fooString, and get back my pointer to foo.
In its completeness...
To address-string
NSString *foo = #"foo";
NSString *address = [NSString stringWithFormat:#"%p", foo];
And back
NSString *fooAgain;
sscanf([address cStringUsingEncoding:NSUTF8StringEncoding], "%p", &fooAgain);
This snippet worked for me:
NSString *pointerString = #"0x809b5c0";
NSObject *object;
sscanf([pointerString cStringUsingEncoding:NSUTF8StringEncoding], "%p", &object);
Convert it to an integer, then cast it to whatever type it's supposed to be...
NSUInteger myInt = [ myStr integerValue ];
char * ptr = ( char * )myInt;
That said, I really don't understand why you will need this...
In my experience its easier to convert the pointer's address to an NSInteger, like this:
MyObject *object=[[MyObject alloc]init];
//...
NSInteger adress=(NSInteger)object;
Now reverse:
MyObject *otherObject=(MyObject*)adress;
Now: object==otherObject
Use an NSMapTable instead:
MyClass* p = [[MyClass alloc]init];
NSMapTable* map = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory valueOptions:NSMapTableStrongMemory];
[map setObject:whateverValue forKey:p];
// ...
for(MyClass* key in map) {
// ...
}

String Operation

If there is an NSString like "com.mycompany.purchase1" How to get only purchase1.
NSString *mainString = #"com.mycompany.purchase1";
-(NSString*)getLastComponent : (NSString*) mainString
{
NSString *string;
//Implementation
return string;//It should return only "purchase1"
}
I tried using lastPathComponent,pathExtension and also i can't use substringToIndex since the string may be of varying length.
Don't want donkim's answer as he is correct. Just showing the implementation I would use
-(NSString*)lastComponentOfString:(NSString*)string separatedByString:(NSString*)separator
{
return [[string componentsSeparatedByString:separator] lastObject];
}
Use
NSString *string = #"com.mycompany.purchase1";
[... lastComponentOfString:string separatedByString:#"."];
You could use the - (NSArray *)componentsSeparatedByString:(NSString *)separator method in NSString. Check to see that NSArray has a count greater than 0 and the last component of it ([array objectAtIndex:[array count] - 1]) will be what you want.
-(NSString*)getLastComponent : (NSString*) mainString
{
NSString *string1;
NSArray *arr=[mainString componentsSeparatedByString:#"."];
string1=[arr objectAtIndex:([arr count]-1)];
return string;
}
use above code.

method with 2 return values

I want to call a method which returns two values
basically lets say my method is like the below (want to return 2 values)
NSString* myfunc
{
NSString *myString = #"MYDATA";
NSString *myString2 = #"MYDATA2";
return myString;
return myString2;
}
So when i call it, i would use??
NSString* Value1 = [self myfunc:mystring];
NSString* Value2 = [self myfunc:mystring2];
I guess im doing something wrong with it, can anyone help me out?
Thanks
You can only return 1 value. That value can be a struct or an object or a simple type. If you return a struct or object it can contain multiple values.
The other way to return multiple values is with out parameters. Pass by reference or pointer in C.
Here is a code snippet showing how you could return a struct containing two NSStrings:
typedef struct {
NSString* str1;
NSString* str2;
} TwoStrings;
TwoStrings myfunc(void) {
TwoStrings result;
result.str1 = #"data";
result.str2 = #"more";
return result;
}
And call it like this:
TwoStrings twoStrs = myfunc();
NSLog(#"str1 = %#, str2 = %#", twoStrs.str1, twoStrs.str2);
You need to be careful with memory management when returning pointers even if they are wrapped inside a struct. In Objective-C the convention is that functions return autoreleased objects (unless the method name starts with create/new/alloc/copy).
You have a few options:
NSArray: Just return an array. Pretty simple.
Pointers: Pass in two pointers, and write to them instead of returning anything. Make sure to check for NULL!
Structure: Create a struct that has two fields, one for each thing you want to return, and return one of that struct.
Object: Same a structure, but create a full NSObject subclass.
NSDictionary: Similar to NSArray, but removes the need to use magic ordering of the values.
As you can only return one value/object, maybe wrap them up in an array:
-(NSArray*) arrayFromMyFunc
{
NSString *myString = #"MYDATA";
NSString *myString2 = #"MYDATA2";
return [NSArray arrayWithObjects:myString,myString2,nil];
}
You can then use it like this:
NSArray *arr = [self arrayFromMyFunc];
NSString *value1 = [arr objectAtIndex:0];
NSString *value2 = [arr objectAtIndex:1];
You could pass results back by reference, but this is easy to get wrong (syntactically, semantically, and from memory management point of view).
Edit One more thing: Make sure that you really need two return values. If they are quite independent, two separate function are often the better choice - better reusabilty and mentainable. Just in case you are making this as a matter of premature optimization. :-)
You can only directly return one value from a function. But there is a way of doing it.
-(void) myfuncWithVal1:(NSString**)val1 andVal2:(NSString**)val2
{
*val1 = #"MYDATA";
*val2 = #"MYDATA2";
}
Then to call it outside the method you'd use:
NSString* a;
NSString* b;
[self myfuncWithVal1:&a andVal2:&b];
void myfunc(NSString **string1, NSString **string2)
{
*string1 = #"MYDATA";
*string2 = #"MYDATA2";
}
...
NSString *value1, *value2;
myfunc(&value1, &value2);
Remember that you need to pass a pointer to a pointer when working with strings and other objects.
Wrap the two strings in an NSArray:
- (NSArray*)myFunc
{
NSString *myString = #"MYDATA";
NSString *myString2 = #"MYDATA2";
return [NSArray arrayWithObjects:myString, myString2, nil];
}
NSArray *theArray = [self myFunc]
NSString *value1 = [theArray objectAtIndex:0];
NSString *value2 = [theArray] objectAtIndex:1];
I see everyone has mentioned an NSArray but I'd go with an NSDictionary so the values don't have to be added in order or even at all. This means it is able to handle a situation where you only want to return the second string.
- (NSDictionary*)myFunction {
NSString *myString1 = #"string1";
NSString *myString2 = #"string2";
return [NSDictionary dictionaryWithObjectsAndKeys: myString1, #"key1", myString2, #"key2", nil];
}
NSDictionary *myDictionary = [self myFunction]
NSString *string1 = [myDictionary objectForKey:#"key1"];
NSString *string2 = [myDictionary objectForKey:#"key2"];