我來自一個Visual Basic的背景(很久以前),所以要溫柔請...新手目標C函數的NSString INT
我工作的一個iPhone應用程序,需要發送一個NSString(我相信這是一個NSString函數,它將把NSString轉換爲一個整數並返回該值,該值可能應該作爲整數返回,因爲Core Data屬性是一個整數)
我需要在UILabel中顯示歌曲的時間,這是一個NSSTring。我將數據作爲一個整數存儲在Core Data屬性中,因爲它更容易對它進行計算等等。我正在做的一件事情將秒(int)轉換爲「3:32」NSString爲標籤。
cell.profileItemsSongDurationLabel.text= ConvertSecondstoMMSS([[managedObject valueForKey:@"profileItemsSongDurationInSeconds"] description]);
// implicit declaration of function 'ConvertSecondstoMMSS' is invalid in C99
// Implicit conversion of 'int' to 'NSString *' is disallowed with ARC
// Incompatible integer to pointer conversion passing 'int' to parameter of type 'NSString *'
- (NSString *)ConvertSecondstoMMSS:(NSString *)songLength // Conflicting return type in implementation of 'ConvertSecondstoMMSS:': 'int' vs 'NSString *'
{
NSString *lengthOfSongInmmss;
int songLengthInSeconds = [songLength intValue];
int hours = songLengthInSeconds/ 3600;
int minutes = (songLengthInSeconds % 3600)/60;
int seconds = songLengthInSeconds % 60;
return lengthOfSongInmmss = [NSString stringWithFormat:@"%d:%02d:%02d", hours, minutes, seconds];
}
很自然,這段代碼有一些問題,但我很感激有關錯誤的一個快速教訓,以及如何解決它。
在此先感謝
- 保羅
修訂方案:
int convertToInt = [[[managedObject valueForKey:@"profileItemsSongDurationInSeconds"] description] intValue];
NSLog(@"convertToInt: %d", convertToInt);
cell.profileItemsSongDurationLabel.text = [self convertSecondstoMMSS:convertToInt];
- (NSString *)convertSecondstoMMSS:(int)songLength
{
NSString *lengthOfSongInmmss;
int hours = songLength/ 3600;
int minutes = (songLength % 3600)/60;
int seconds = songLength % 60;
return lengthOfSongInmmss = [NSString stringWithFormat:@"%d:%02d:%02d", hours, minutes, seconds];
}
唯一剩下的項目解決的是lengthOfSongInmmss的情況。很少會有一首歌持續一個小時,它只是爲了「以防萬一」有沒有辦法通過字符串格式顯示小時,或者最好是做一個簡單的「if」語句?
再次感謝!
'[managedObject valueForKey:]'雖然返回一個'(id)',但不是一個int。OP將需要做'[(NSNumber *)[managedObject valueForKey:@「profileItemsSongDurationInSeconds」] intValue]' – commanda 2012-02-17 03:01:36
感謝您指出:) – 2012-02-17 03:35:50