2012-02-17 103 views
0

我來自一個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」語句?

再次感謝!

回答

2

爲了解決這個錯誤:

由於NSManagedObject將返回一個整數,這樣做:

cell.profileItemsSongDurationLabel.text = [self ConvertSecondstoMMSS:[managedObject valueForKey:@"profileItemsSongDurationInSeconds"]]; 

然後改變方法聲明,以期待一個整數,如:

-(NSString *)ConvertSecondstoMMSS:(int)songLength 

並使用像這樣的方法直接整數:

int hours = songLength/3600; 
+1

'[managedObject valueForKey:]'雖然返回一個'(id)',但不是一個int。OP將需要做'[(NSNumber *)[managedObject valueForKey:@「profileItemsSongDurationInSeconds」] intValue]' – commanda 2012-02-17 03:01:36

+0

感謝您指出:) – 2012-02-17 03:35:50

0

您需要創建一個NSString類別,然後執行該解決方法。

但是,根據您需要使用該功能的次數,可能會更快地直接在需要信息的方法中實現它,而不是創建類別等等。

2

您沒有正確調用您的轉換方法。你將C函數調用語法與Objective-C方法調用語法混合在一起。下面是調用函數的正確方法:

cell.profileItemsSongDurationLabel.text = [self ConvertSecondstoMMSS:[[managedObject valueForKey:@"profileItemsSongDurationInSeconds"] description]; 

假設ConvertSecondstoMMSS與該行在同一個類中。

此外,你應該駱駝案件的方法名稱。將其重命名爲convertSecondsToMMSS。

+0

感謝您的回覆。 – 2012-02-17 13:15:06