Re: Conversion from object to NSString
Re: Conversion from object to NSString
- Subject: Re: Conversion from object to NSString
- From: James Bucanek <email@hidden>
- Date: Thu, 27 Jan 2005 08:22:08 -0700
John Cebasek wrote on Thursday, January 27, 2005:
>Hi All:
>
>I've got an NSArray that gets populated with a bunch of Strings. If
>later on, I want to get back to the strings, I do:
>
> int nIndex = [tokenList_ indexOfSelectedItem];
> id anObject = [serialNumberArray objectAtIndex:nIndex];
>
>So, I thought I'd try to get it back into a readable form with (the
>length = 100 is just a guess):
>
> NSMutableString *serialNumberString = [[NSString alloc]
>initWithBytes:anObject length:100];
>
>But that doesn't work. So how does on get from an object to a NSString?
'anObject' *is* an NSString already. Objects put in an NSMutableArray don't suddenly become something else. The NSArray only keeps a reference to the objects you put in it. If you put in NSStrings:
NSString* aString = @"hi!";
[someArray addObject:aString];
... then that's exactly what you're going to get out:
NSString* bString = (NSString*)[someArray firstObject];
For your code, you only need to change the NSString to an NSMutableString if you want to manipulate it:
NSMutableString *serialNumberString = [NSMutableString stringWithString:anObject];
If you don't need to manipulate it, then you don't have to do anything (except maybe cast it as an NSString* for compile-time type checking).
Note also that in your example you declared serialNumberString to be an NSMutableString, but tried to create an NSString. I assume this was a typo.
--
James Bucanek <mailto:email@hidden>
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden