开发者

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]
                        i开发者_如何学JAVAnitWithString:@"http://example.com/prova/"];

[url appendString:num];


-[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];


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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜