user1277194
user1277194

Reputation:

How to copy from NSMutableArray to NSMutableString?

Im trying to add some strings into NSMutableArray,than want to copy element 0(zero) from NSMutableArray to NSMutableString

[MS appendString:str]

this line raises error.

what is the problem ? a MutableArray element cannot be assigned to NSString ? (thanks for any responses)

error output is :

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

here is my code :

NSMutableArray *A=[[NSMutableArray alloc]init];
NSMutableString *MS=[NSMutableString stringWithString:@"first"];

for (int i=0; i<=15;i+=2) {
    [A addObject:[NSNumber numberWithInteger:i]];
}

NSString *str;

for (int x=0; x<[A count]; x++) {
    str=[A objectAtIndex:0];
    [MS appendString:str];//ERROR HERE
}

[A release];

Upvotes: 0

Views: 357

Answers (1)

sch
sch

Reputation: 27506

You are adding NSNumbers to the array and not strings n the folioing line:

[A addObject:[NSNumber numberWithInteger:i]]; // here you are adding numbers

So when you read them from the array later, they are still numbers and you have to create strings from them:

NSString *str;
NSNumber *number;

for (int x=0; x<[A count]; x++) {
    number = [A objectAtIndex:0]; // You should probably replace 0 by x here.
    str = [number stringValue]; // transform number into a string
    [MS appendString:str];
}

[A release];

But if you want the array to store strings and not numbers, then replace the first loop instead with the following:

for (int i=0; i<=15;i+=2) {
    [A addObject:[[NSNumber numberWithInteger:i] stringValue]];
}

Or

for (int i=0; i<=15;i+=2) {
    [A addObject:[NSString stringWithFormat:@"%d", i]];
}

Upvotes: 2

Related Questions