Я просто хочу изменить переменную объекта из другого класса.Я могу скомпилировать без проблем, но моя переменная всегда имеет значение «ноль».Я использовал следующий код:
Object.h:
@interface Object : NSObject {
//...
NSString *color;
//...
}
@property(nonatomic, retain) NSString* color;
+ (id)Object;
- (void)setColor:(NSString*)col;
- (NSString*)getColor;
@end
Object.m:
+(id)Object{
return [[[Object alloc] init] autorelease];
}
- (void)setColor:(NSString*)col {
self.color = col;
}
- (NSString*)getColor {
return self.color;
}
MyViewController.h
#import "Object.h"
@interface ClassesTestViewController : UIViewController {
Object *myObject;
UILabel *label1;
}
@property UILabel *label1;
@property (assign) Object *myObject;
@end
MyViewController.m:
#import "Object.h"
@implementation MyViewController
@synthesize myObject;
- (void)viewDidLoad {
[myObject setColor:@"red"];
NSLog(@"Color = %@", [myObject getColor]);
[super viewDidLoad];
}
Сообщение NSLog всегда Color = (null)
Я пробовал много разных способов решить эту проблему, но безуспешно.Буду признателен за любую помощь.
Спасибо за помощь.
Я изменил код следующим образом, но он все еще не работает, как следует.
MyViewController.h:
#import <UIKit/UIKit.h>
#import "Object.h"
@interface MyViewController : UIViewController {
Object *myObject;
}
@property (nonatomic, retain) Object *myObject;
@end
MyViewController.m:
#import "MyViewController.h"
#import "Object.h"
@implementation MyViewController
@synthesize myObject;
- (void)viewDidLoad {
Object *myObject = [Object new];
myObject = 0;
[myObject setColor:@"red"];
NSLog(@"color = %@", myObject.color);
[super viewDidLoad];
}
Если я сделаю это так, NSLog вернет color = null
(и я думаю, что myObject
виден только в viewDidLoad).Как можно объявить myObject
и сделать его видимым в MyViewController?Я сократил свой класс Object до
Object.h:
@interface Object : NSObject {
NSString *color;
}
@property(nonatomic, retain) NSString *color;
@end
Object.m:
#import "Object.h"
@implementation Object
@synthesize color;
@end
Я не смог определить объект myObject
в ViewDidLoad, чтобы я мог получить доступ к его свойствам из всего класса ViewController?Что я упустил?Дополнительный вопрос: почему я должен установить myObject на 0?