如何在Objective C中从另一个类更改类变量?

时间:2010-04-07 15:04:05

标签: iphone objective-c xcode

我只想从另一个类中更改对象的变量。我可以编译没有问题,但我的变量总是设置为'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?

1 个答案:

答案 0 :(得分:3)

  1. 您正在声明一个属性,然后在Object.h中明确声明访问器。你只需要做一个或者另一个 - 它们的意思相同(好吧,几乎 - 你将color而不是getColor
  2. 要在Object.m中实现该属性,您应该使用@synthesize color。然后,显式实现是多余的(除非他们做任何额外的事情)。
  3. Object.m中的显式setColor实现正在调用属性 - 您正在显式实现它,所以我希望您在此处获得无限递归。
  4. MyViewController.m可能应该合成label1,因为你在标题中声明了属性(尽管它没有在你的代码片段中使用)。
  5. [myObject getColor]正在调用您声明但未合成的color属性。如果你已经明确地将其实现为color,它就会选择它 - 但它不会匹配getColor(幸运的是,这会导致无限递归。
  6. 我没有看到你在哪里创建myObject实例。如果不这样,它将是nil,并且调用它的方法(包括属性访问)将返回0或nil。
  7. 我怀疑(6)是你问题的原因,但其他问题也需要解决。请务必阅读属性语法。