1

i use xcode 9

NSMutableArray *Upcase_Keys = @[@"1",@"2",@"3",@"4,"@"5",@"6",@"7",@"8",@"9",@"0"]; 
NSString *str = [Upcase_Keys objectAtIndex:0];
str = @"test";
[Upcase_Keys replaceObjectAtIndex:0 withObject:str];

Gets specific data for NSMutableArray

It transforms the value and overwrites the existing index.

However, this code causes a crash.

What did I do wrong?

2 Answers 2

2

NSMutableArray replaceObjectAtIndex Crash

So there should be an error in console. Console will help you 99% of the cases when there is a crash, read it! It should be something like -[NSArrayI replaceObjectAtIndex:withObject:] unrecognized selector sent to instance. That's the important part of your error. NSArrayI meaning NSImmutableArray (NSArray in other words), which is not a NSMutableArray which points out that the issue is about the creation of Upcase_Keys.

Why then? Because @[@"1",@"2",@"3",@"4,"@"5",@"6",@"7",@"8",@"9",@"0"]; that's a short hand syntax for NSArray, not NSMutableArray. So even if it's declared as a NSMutableArray, the object is in fact a NSArray. In fact, if you'd listen to XCode, it should give you this warning:

Incompatible pointer types initializing 'NSMutableArray *' with an expression of type 'NSArray *'

Which concords with everything said before.` Sometimes XCode may be wrong, but try to listen to it.

There are a few possibilities call:

NSMutableArray *Upcase_Keys = [NSMutableArray arrayWithArray:@[@"1",@"2",@"3",@"4,"@"5",@"6",@"7",@"8",@"9",@"0"]];
NSMutableArray *Upcase_Keys = [[NSMutableArray alloc] initWithArray:@[@"1",@"2",@"3",@"4,"@"5",@"6",@"7",@"8",@"9",@"0"]];
NSMutableArray *Upcase_Keys = [@[@"1",@"2",@"3",@"4,"@"5",@"6",@"7",@"8",@"9",@"0"] mutableCopy];

And finally, a recommendation use camelcase: Avoid naming your var with an uppercase. Use a lower case for the first letter. I'd say that after the _ is less problematic, but we tend in iOS to write instead.

Upcase_Keys => upcase_Keys => upcaseKeys

Sign up to request clarification or add additional context in comments.

Comments

0

You have defined as immutable object, The syntax will assign NSArray reference not NSMutableArray. You can't update the NSArray.

Try like this,

NSMutableArray *Upcase_Keys = [NSMutableArray arrayWithArray:@[@"1",@"2",@"3",@"4,"@"5",@"6",@"7",@"8",@"9",@"0"]];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.