开发者

Assign to NSString after alloc/init

开发者 https://www.devze.com 2023-03-11 13:07 出处:网络
This doesn\'t seem to work: NSString *string = [[NSString alloc] init]; string = @\"%@M\", anotherstring;

This doesn't seem to work:

NSString *string = [[NSString alloc] init];
string = @"%@M", anotherstring;

I expect this to make "string" equal to "5M" if "anotherstring" is "5".

Is this not the right 开发者_如何学Pythonsyntax? Now, I could use initWithFormat and it would work, but how can you separate it into two different lines and also work?


There are two mistakes in your code. Firstly, NSStrings are immutable, and once you allocate and initialize them, they're set, and there's no way to change them. For that, you'd have to look into NSMutableString.

Secondly, the syntax of your code makes no sense. @"%@M", anotherString is not a valid Objective-C method call. You are indeed looking for -initWithFormat: to perform the operation you want. The code should look like this:

NSString *string = [[NSString alloc] initWithFormat:@"%@M", anotherString];

Read more about NSString and how to use it in the NSString Programming Reference document, and the String Programming Guide to get a sense of how to work with strings in Cocoa and Objective-C.


This line:

string = @"%@M", anotherstring;

is syntactically correct, but it doesn't do what you want it to do. This is how you format a string:

NSString *string = [[NSString alloc] initWithFormat:@"%@M", anotherstring];

There's no point in separating it into two lines. This:

NSString *string = [[NSString alloc] init];
string = [[NSString alloc] initWithFormat:@"%@M", anotherstring];

will create an extra NSString object, and also cause a memory leak.


How about

NSString* string;
string = [[NSString alloc] initWithFormat:@"%@M", anotherString];

Keep in mind that the = operator is assignment. Any time you use it, any value was stored in your variable is overwritten with the new one. So even if your original code was syntactically correct it still has faulty semantics that would, in this case, cause a memory leak.


just make it into a property and you dont need to worry about releasing and retaining the "string" (that is if you autocreate it by using synthesize). and dont forget to autorelease the object ur assigning to the property:

self.string = [[[NSString alloc] init] autorelease]

0

精彩评论

暂无评论...
验证码 换一张
取 消