KopBob
KopBob

Reputation: 1151

How to set UILabel text from another class

I have problem with UILabel . Here is two file's ViewController and MainClass first is controller for nib file with label1 outlet. Second file is a class with another label mainLabel which contain text("Set from init method in MainClass"). I want set mainLabel to label1 in ViewController.

In init method of MainClass i set text for mainLabel.text

mainLabel.text = @"Set from init method in MainClass";

and after that i call NSLog(@"%@",mainLabel.text); but in console i have null

2011-12-14 10:31:31.048 ClassTask[1076:f803] (null)

and after then i call label1 = newClass.mainLabel; in - (void)viewDidLoad i have view with label1 without text in my iPhone simulator. // ViewController.h

#import <UIKit/UIKit.h>
#import "MainClass.h"
@interface ViewController : UIViewController {
    UILabel *label1;    
    MainClass *newClass;
}
@property (nonatomic, retain) IBOutlet UILabel *testLabel;
@end

// ViewController.m

#import "ViewController.h"
@implementation ViewController
@synthesize label1;
-(void) dealloc{
    [label1 release];
    [super dealloc];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    newClass = [MainClass new];
    label1 = newClass.mainLabel;
}
@end

// MainClass.h

#import <UIKit/UIKit.h>
@interface MainClass : NSObject {
    UILabel *mainLabel;
}
@property (nonatomic, retain) IBOutlet UILabel *mainLabel;
@end

// MainClass.m

#import "MainClass.h" @implementation MainClass @synthesize mainLabel;
-(id) init {
    if (self = [super init]) {
        mainLabel.text = @"Set from init method in MainClass";
        NSLog(@"%@",mainLabel.text);
    }
    return self; }
-(void)dealloc {
    [mainLabel release];
    [super dealloc]; 
} 
@end

Upvotes: 0

Views: 1696

Answers (2)

Shahab Qureshi
Shahab Qureshi

Reputation: 950

Why don't you make it a NSString , its basically a text that you want to access in another ViewController.

another mistake i found

#import "ViewController.h"
@implementation ViewController
@synthesize label1;
-(void) dealloc{
    [label1 release];
    [super dealloc];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    newClass = [MainClass new];
    **label1 = newClass.mainLabel.Text;  // its a label, so whenever you retrieve its value it would be like labelName.Text**
}
@end

Upvotes: 1

Emon
Emon

Reputation: 958

I think if you want to pass this string [in your code it mainLabel.text] from one controller to another controller then you can use UISharedApplication..follow this link.... https://stackoverflow.com/questions/8486540/i-want-to-pass-data-from-one-view-controller-to-another-controller/8487095#8487095

Upvotes: 0

Related Questions