iOS using nsstring from class in UIViewController
I've been bashing my head against this for a week solid, I'm sure its been answered before but in all my research i'm just confusing myself more and more.
I'm just simply trying to use an NSString from a class (BBDate) in a UILabel in my main UIViewController.
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 ju开发者_如何学Gost using viewdidload
- (void)viewDidLoad {
[super viewDidLoad];
dateToday.text = bbDate.dateString;
NSLog(@"%@", bbDate.dateString);
...
You need to initialize bbDate for one thing and create a date:
bbDate = [[BBDate alloc] init];
[bbDate createDate];
Put that before:
dateToday.text = bbDate.dateString;
Also:
- (void)createDate; {
Get rid of the semicolon:
- (void)createDate {
In your createDate method:
dateString = string;
Should be:
self.dateString = string;
Plus you probably are not going to need the NSDateFormatter outside your method so at the end of it say:
[formatter release];
精彩评论