我只想从另一个类中更改对象的变量。我可以编译没有问题,但我的变量总是设置为'null'。 我使用了以下代码:
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
我无法在ViewDidLoad中定义对象myObject
,以便我可以从整个ViewController类访问其属性?我错过了什么?
附带问题:为什么我必须将myObject设置为0?
答案 0 :(得分:3)
color
而不是getColor
)@synthesize color
。然后,显式实现是多余的(除非他们做任何额外的事情)。setColor
实现正在调用属性 - 您正在显式实现它,所以我希望您在此处获得无限递归。label1
,因为你在标题中声明了属性(尽管它没有在你的代码片段中使用)。color
,它就会选择它 - 但它不会匹配getColor
(幸运的是,这会导致无限递归。nil
,并且调用它的方法(包括属性访问)将返回0或nil。我怀疑(6)是你问题的原因,但其他问题也需要解决。请务必阅读属性语法。