NSMutableArray的转换和求和时间间隔

时间:2013-01-25 19:27:36

标签: objective-c loops nsmutablearray

我对Objective-C很新,需要一些帮助。我有一系列歌曲:

   {
    artist = "Bernard Herrmann";
    duration = "2:34";
    id = 5;
    title = "Torn Curtain: The Unused Score";
},
    {
    artist = "Miklos Razsa";
    duration = "3:47";
    id = 6;
    title = "Ivanhoe [Original]";
},
...etc.

我想遍历数组,将持续时间(当前为NSStrings)转换为可以用来表示实际经过时间的内容,然后将它们相加以便我可以得到总数是时候播放播放列表了。我已经开始研究循环了:

更新:

- (NSInteger)convertDuration
{
    NSInteger totalSeconds=0;
    for(NSMutableArray *song in playlist){
        NSString *durationString = [playlist valueForKey:@"duration"];
        NSArray *breakMinSec = [durationString componentsSeparatedByString:@":"];
        NSInteger sec = [breakMinSec[1]integerValue];
        NSInteger min = [breakMinSec[0]integerValue];
        totalSeconds += ( sec + min * 60 );
        }
    return totalSeconds;
}

现在看来,durationString正在拉动第一次迭代中的所有持续时间。它不会像这样编译。我怎样才能确定每次迭代只能获得一个持续时间?

1 个答案:

答案 0 :(得分:0)

这里无需将其转换为NSTimeInterval或NSDate。您只需将所有持续时间添加到数组即可。然后打破分钟和秒钟,添加所有分钟和所有秒数。

然后

 totalSeconds%=60;
 totalMinutes+=totalSeconds/60;

编辑:一个想法如何做(不是编译器检查)

//NSMutableArray *durationArray=[NSMutableArray new];
NSInteger totalseconds=0;
for(NSDictionary *song in songDict){
    NSString *durationString=song[@"duration"];
    NSArray *breakMinSec=[durationString componentsSepartedByString:@":"];
    NSInteger sec=[breakMinsec[1]integerValue];
    NSInteger min=[[breakMinSec[0]integerValue];
    //[durationArray addObject:@[sec+min*60]];
    totalseconds+=(sec+min*60);
}

这将以秒为单位存储每首歌曲的时间。然后你可以根据你的需要制作这个值。

编辑:

看到你的编辑后:

  

我怎样才能确定每次迭代只能获得一个持续时间?

您可以向方法发送一个值,该值将返回该特定歌曲的持续时间。或者在我之前的回答中,每个持续时间都保存在基于索引的数组中,您可以从那里轻松检索。

相关问题