davideagostini
davideagostini

Reputation: 121

Append a NSString to a NSMutableString, raises an exception

I access to a specific element of a NSMutableArray (nid) and save it in a NSString (num).

After that I want concatenate this element (num) with a url (NSMutableString), and use the method appendString but I obtain an exception.

how can I fix this?

below the code:

NSMutableArray nid; 
....

NSUInteger row = [indexPath row];
NSString *num = [nid objectAtIndex:row];

NSMutableString *url = [[NSMutableString alloc]
                        initWithString:@"http://example.com/prova/"];

[url appendString:num];

Upvotes: 1

Views: 3106

Answers (2)

albertamg
albertamg

Reputation: 28572

-[NSCFNumber length]: unrecognized selector sent to instance 0x4b54de0 * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFNumber length]: unrecognized selector sent to instance 0x4b54de0'

As per the exception, it looks like objectAtIndex: is returning a NSNumber instead of a NSString. If nid contains numbers, you need to convert them to strings before you can pass them to appendString:

NSUInteger row = [indexPath row];
NSNumber *num = [nid objectAtIndex:row];
NSString *numStr = [num stringValue];

NSMutableString *url = [[NSMutableString alloc]
                        initWithString:@"http://example.com/prova/"];

[url appendString:numStr];

...

[url release];

Upvotes: 4

Jhaliya - Praveen Sharma
Jhaliya - Praveen Sharma

Reputation: 31730

nid is an array which return an number not an NSString , so an NSNumber is being returned by the below statement

NSString *num = [nid objectAtIndex:row]; // Wrong statement 

NSNumber* num = [nid objectAtIndex:row]; // Correct statement 

So your code should be ..

NSMutableArray nid; 
....

NSUInteger row = [indexPath row];

//your array contain NSNumber type of pointer NOT NSString.
NSNumber *num = [nid objectAtIndex:row];

//Get a NSString object from a NSNumber.
NSString *myString = [num stringValue];

NSMutableString *url = [[NSMutableString alloc]
                        initWithString:@"http://example.com/prova/"];

[url appendString:myString];

Upvotes: 1

Related Questions