2011-08-13 54 views
0

我一直在抨擊我的頭一個星期堅實,我敢肯定它的答案之前,但在我所有的研究中,我只是越來越多地困惑自己。iOS使用UIViewController中的類的nsstring

我只是簡單地嘗試從UMLabel中的類(BBDate)在我的主要UIViewController中使用NSString。

BBDate.h

#import <Foundation/Foundation.h> 
@interface BBDate : NSObject { 
    NSString *dateString; 
} 
@property (nonatomic, retain) NSString *dateString; 
@end 

BBDate.m

//just a simple date creation and formatting to try to learn this technique 
#import "BBDate.h" 
@implementation BBDate 
@synthesize dateString; 

- (void)createDate; { 
NSDate* date = [NSDate date]; 
//Create the dateformatter object 
NSDateFormatter* formatter = [[NSDateFormatter alloc] init]; 
//Set the required date format 
[formatter setDateFormat:@"MM-dd-yyyy"]; 
//Get the string date 
NSString *string = [formatter stringFromDate:date]; 
//Display on the console 
    NSLog (@"%@",string); 
    //set variable 
    dateString = string; 
    } 
    @end 

UIViewController.h

#import <UIKit/UIKit.h> 
#import "BBDate.h" 

@interface BBFirstViewController : UIViewController { 

UILabel *dateToday; 
BBDate *bbDate; 
} 
@property (nonatomic, retain) IBOutlet UILabel *dateToday; 
@property (nonatomic, retain) BBDate *bbDate; 
@end 

UIViewController.m

#import "BBFirstViewController.h" 
#import "BBDate.h" 
@implementation BBFirstViewController 
@synthesize dateToday, bbDate; 
... 
//for testing i'm just using viewdidload 
- (void)viewDidLoad { 
[super viewDidLoad]; 
dateToday.text = bbDate.dateString; 
NSLog(@"%@", bbDate.dateString); 
... 

回答

0

需要初始化bbDate一兩件事,並創建一個日期:

bbDate = [[BBDate alloc] init]; 
[bbDate createDate]; 

端起面前:

dateToday.text = bbDate.dateString; 

另外:

- (void)createDate; { 

擺脫分號:

- (void)createDate { 

In您CREATEDATE方法:

dateString = string; 

應該是:

self.dateString = string; 

另外,你可能都不會需要NSDateFormatter你的方法以外,以便在它的末尾說:

[formatter release]; 
+0

和' [formatter release]'和'self.dateString = string' –

+0

@Evgeniy:感謝您指出其他一些問題。 – Dair

+0

真棒謝謝一噸。我知道我必須分配/初始化類,但不確定語法,我沒有發現錯誤的分號。還我使用ARC,所以我不需要釋放對象。我還必須將 - (void)createDate添加到BBDate.h以供vc查看。再次感謝,我終於明白了! – BigB