开发者

How would I display every iteration of this for loop? Objective C

开发者 https://www.devze.com 2023-02-24 04:07 出处:网络
I\'m still learning the basic syntax of Objective C, so this answer is probably obvious. What i\'m trying to do here is have display.text equal all o开发者_如何学编程f the instances of \"newtext\" (ev

I'm still learning the basic syntax of Objective C, so this answer is probably obvious. What i'm trying to do here is have display.text equal all o开发者_如何学编程f the instances of "newtext" (every time "i" changes) in a list.

    NSArray *newsArray = [NSArray arrayWithObjects: @"news", @"latest", @"trending", @"latebreaking", nil];
        for(int i=0; i<4; ++i)
        {
            NSString *newText = [NSString stringWithFormat:@"%@%@\n", [newsArray objectAtIndex: i],[sufField text]];
            display.text = newText;
        }

Thanks!


The answer depends on what display.text is. If it is a immutable string:

• a read/write object property (e.g. property (readwrite, assign) NSString *text;); or

• a field of a structure (e.g. struct { NSString *text; ... })

then the core of what you need to do is create a new string by appending newText:

display.text = [display.text stringByAppendingString:newText];

If you are using automatic garbage collection then you're done.

If not you need to know the ownership of display.text. Assuming display.text owns its value (the usual case) and the property or struct field is defined as above then the code becomes:

NSString *oldText = display.text;
display.text = [[oldText stringByAppendingString:newText] retain]; // create new string and retain
[oldText release]; // release previous value

Now in the property case you can define the property itself to do the retain/release, by defining it as:

property (readwrite, retain) NSString *text;

and then the appending is back to:

display.text = [display.text stringByAppendingString:newText];

Now display.text might be a mutable string, which is a good idea if you plan on appending a lot of values to it, that is it is:

• a read/write object property (e.g. property (readwrite, assign) NSMutableString *text;); or

• a field of a structure (e.g. struct { NSMutableString *text; ... })

then you append a new string using:

[display.text appendString:newText];

and that is it. (In the property case it doesn't matter if retain is specified - the code is the same.)

The differences between automatic garbage collection, object ownership, and immutable and mutable types is at the core of understanding the semantics of Objective-C - understand all these cases and you'll be well on you way!

0

精彩评论

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