3

I am new to Objective C. we can create String Object by one of these. can anybody tell difference & which is best,simplest way to doing this?

NSString *simpleString = @"This is a simple string";
NSString *anotherString = [NSString stringWithString:@"This is another simple string"];
NSString *oneMorestring = [[NSString alloc] initWithString:@"One more!"];
NSMutableString *mutableOne = [NSMutableString stringWithString:@"Mutable String"];
NSMutableString *anotherMutableOne =[[NSMutableString alloc] initWithString:@"A retained one"];
NSMutableString *thirdMutableOne =[NSMutableString stringWithString:simpleString];
0

3 Answers 3

2

The First method is the simplest and best method for creating string instance if the string is constant. The first method is also prefer as it follow Modern Objectice-C Language.

The Main deference between NSString and NSMutableString is that NSString object is constant. and we can't change or update its value. But NSMutableString has property to change or updates its value.

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

Comments

2

It really depends on what you want to do.

For simply creating a string from a constant, your first example is best.

stringWithString pretty much just creates a copy of a string, so I don't use it much.

You might want to check out stringWithFormat and stringByAppendingString. Those are two that I use most often.

If you enable ARC, then you don't need to worry about retaining strings. Alloc/init or class factory methods are essentially equivalent under ARC, so use whichever you like best.

Comments

1

There is nothing a best way... It is upto our requirement. However most of the time we opt for manual allocated and initized version of NSString or NSMutableString.

First 3 are Constant String, next three are String which you can manipulate.

Line number 1: is simply a const string.

Line number 2: You are copying a const string you anotherString.

Line number 3: You are manually allocating and initializing it. Its upto you or ARC(compiler) to release it.

Similarly with rest Mutable versions.

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.