NSMutableArray对象添加到字符串

时间:2015-08-24 09:13:23

标签: iphone xcode nsmutablearray

我有3个或更多数据的NSMutableArray。我需要String这个数据,如:“data1,data2,data3”。

我的代码:

for(int x=0; x<data.count;x++)
    {  
      NSString *string = [data objectAtIndex:x]; 
    }

3 个答案:

答案 0 :(得分:1)

我已经看到了其他解决方案......这个解决方案突然出现在我脑海中;我不明白为什么这个解决方案不够好,因为它看起来更复杂,更优雅:

NSArray *_myArray = [NSArray arrayWithObjects:@"item-1", @"item-2", @"item-3", nil];
NSString *_myString = [_myArray componentsJoinedByString:@", "];

最终结果将是:

item-1, item-2, item-3

注意:当然,输入数组也可以是NSMutableArray,它不会影响最终输出。

答案 1 :(得分:0)

NSMutableArray *data = [[NSMutableArray alloc] initWithObjects:@"data1", @"data2", @"data3", nil];
NSMutableString *finalString = [[NSMutableString alloc]  init];

for (int x = 0; x < data.count; x++)
{
    NSString *string = [data objectAtIndex:x];
    [finalString appendFormat:x == data.count-1 ? @"%@" : @"%@,", string];
}

NSLog(@"finalString: %@", finalString);

答案 2 :(得分:-1)

你的意思是你想把所有数据加入一个字符串吗?

如果我是对的,请输入以下代码:

 <div class="row" ng-controller="OverviewCtrl">
    <div class="col-md-5" > 
        <div class="panel panel-default">
            <div class="panel-heading"><h4>List 1</h4></div>
            <div class="panel-body">
                <ul class="list-group">
                    <li class="list-group-item" ng-repeat="item in list1" ng-click="toggle(item.title)" >{{item.title}}</li>
                </ul>
            </div>
        </div>

    </div>
    <div class="col-md-2" style="text-align: center"> 
        <button type="button" class="btn btn-success"  style="margin-top: 70px; margin-bottom: 10px">
            <span class="glyphicon glyphicon-triangle-right btn-sm" aria-hidden="true"></span>
        </button>
        </br>
        <button type="button" class="btn btn-success"  style="margin-top: 10px; margin-bottom: 10px">
            <span class="glyphicon glyphicon-triangle-left btn-sm" aria-hidden="true"></span>
        </button>
    </div>
    <div class="col-md-5">
        <div class="panel panel-default">
            <div class="panel-heading"><h4>List 2</h4></div>
            <div class="panel-body">
                <ul class="list-group">
                   <li class="list-group-item" ng-repeat="item in list2" >{{item.title}}</li>
                </ul>
            </div>
        </div>
    </div>
</div>