开发者

Building an NSstring out of an NSMutableArray

My eyes hurt from hours of trying to figure this one - and i have looked for an answer for quite a while on-line (it will be embarrassing to tell how much...). all i am trying to do is to enumerate using a for-in loop on anExpression which is a NSMutableArray that holds NSNumbers and NSStrings. my NSLog print for the variable ans returns an empty string. What am i doing wrong?

  NSString *ans = @"";
    for (id obj in anExpression)
    {
        if ([obj isKindOfClass:[NSString class]])
            [ans stringByAppendingString:(NSString *)obj];
        if ([obj isKindOfClass:[NSNumber class]])
            [ans stringByAppendingString:(NSString *)[obj stringValue]];

        NSLog(@"String so far: 开发者_运维知识库%@ ", ans);
    }


I think you mean

ans = [ans stringByAppendingString:(NSString *)obj];

not just

[ans stringByAppendingString:(NSString *)obj];

NSStrings are immutable -- you can't append to them. -stringByAppendingString: returns a new string (which you could then assign to ans).

Alternatively, you might use an NSMutableString and the -appendString: method.


Hey, sorry for the bad coding format, posting it again ...

NSString *ans = @"";
for (id obj in anExpression)
{
    if ([obj isKindOfClass:[NSString class]])
        [ans stringByAppendingString:(NSString *)obj];
    if ([obj isKindOfClass:[NSNumber class]])
        [ans stringByAppendingString:(NSString *)[obj stringValue]];

    NSLog(@"String so far: %@ ", ans);
}
[ans autorelease];
NSLog(@"final string is: %@ ", ans);

return ans;


the method stringByAppendingString: returns a new string made by appending the given string to the receiver.

so you want ans = [ans stringByAppendingString:obj];

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜