views:

118

answers:

2

Ola Folks,

I want to populate an NSMutableString at runtime by both assigning a specific number (0-255) to an element and appendFormat to add to the string.

If this were an unsigned char array, I could just directly assign the number using:

UnsignedCharRay[SomeIndex] = 5;

For reasons I think I understand but do not like,

NSMutableStringObject[SomeIndex] = 5;

will not work.

As far as I can tell, there are no NSString or NSMutableString methods to directly set an element of the string array.

Is there a way to do this? If so, what is it?

Until I find an answer and can do this with NSMutableString, I am going to use an unsigned char array and create an NSString using the unsigned char araay. Aside from specifying NSUTF8StringEncoding when I create the NSString, are there other considerations I should pay attention to? What is the most effective method of creating an NSString from an unsigned char array? The goal is to retain the values of 0 to 255 during the conversion. Note: 0 would only appear at the end of the string ... sometimes.

TIA

-isdi-

A: 

You probably want to look at the replaceCharactersInRange:withString: method of NSMutableString. It is the closest thing to setting a char[] element directly, you just give it a range of length 1.

Also, you may want to simply create a bunch of strings using initWithFormat:Arguments: and then concatenate them together at the end.

Don't forget that NSString is a complex class, which is designed to provide all sorts of features, memory management, UTF-8 support, I/O, and lots more. It's not really intended to be an open buffer that you write directly to. If you really need to do direct manipulation of bytes, perhaps you are better off just using a char[] buffer to assemble your results, and converting it to an NSString at the end, before you need to display it?

gavinb
+1  A: 

You can use replaceCharactersInRange:withString: to set a specific character at an index, if that is all you're trying to do.

eg

[myMutableString replaceCharactersInRange:NSMakeRange(index,1) withString: value];

However if you just want to store arbitrary char values in an array, you're probably best just doing what you're already doing.

Tom
In the end, I'm going to leave it the way it is. Just in case someone finds this useful: sSendBuff = [[NSMutableString alloc] initWithBytes: sBuffTemp length: strlen(sBuffTemp) encoding: NSUTF8StringEncoding];
ISDi