views:

428

answers:

3

hi, is it an possible to add a value from an NSMutableString into an NSArray? Whats the snippet?

+1  A: 

NSArray is immutable, so you cannot add values to it. You should use NSMutableArray in order to do that with the addObject: method.

NSMutableString *str = ...
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:str];
Laurent Etiemble
+2  A: 

If you want to instantiate an NSArray with a single NSMutableString object, you can do the following:

NSString *myString; //Assuming your string is here
NSArray *array = [NSArray arrayWithObjects:myString,nil];

Note that NSArray will be immutable - that is, you can't add or remove objects to it after you've made it. If you want the array to be mutable, you'll have to create an NSMutableArray. To use an NSMutableArray in this fashion, you can do the following:

NSString *myString; //Assuming your string is here
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:myString];
Mike
+2  A: 

Actually, Mike is wrong. If you want to instantiate an NSArray with a single NSMutableString object, you can do the following:

NSMutableString *myString; //Assuming your string is here
NSArray *array = [NSArray arrayWithObject:myString];

There is no arrayWithElements in NSArray (see NSArray documentation)

Adam Woś
Sorry about the typo. My example is fixed, using the `arrayWithObjects` method.
Mike