2010-04-07 83 views
1

我只是想改變另一個類的對象的變量。我可以編譯沒有問題,但我的變量總是被設置爲'null'。 我用下面的代碼:如何簡單地從ObjectiveC中的另一個類中更改類變量?

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.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?

回答

3
  1. 您聲明瞭一個屬性,然後在Object.h中顯式聲明訪問器。你只需要做一個或另一個 - 他們的意思是相同的(好吧,幾乎 - 你將有color而不是getColor
  2. 要實現Object.m中的屬性,您應該使用@synthesize color。顯式實現又是多餘的(除非它們做了額外的事情)。
  3. Object.m中明確的setColor實現調用了屬性 - 您明確實現了該屬性,所以我希望您在此處獲得無限遞歸。
  4. MyViewController.m應該可能合成label1,因爲您在標頭中聲明屬性(儘管它沒有在您的代碼段中使用)。
  5. [myObject getColor]正在調用您聲明但未合成的顏色屬性。如果你明確地實現它作爲color它會選擇這個 - 但它不會匹配getColor(幸運的是,因爲這將導致無限遞歸。
  6. 我沒有看到任何地方你創建你的myObject的實例。如果沒有這將是nil和方法調用了它(包括屬性訪問)將返回0或零。

我懷疑(6)是你的問題的原因,但其他人需要請確保你閱讀了屬性語法

+0

並且'@synthesize myObject;'的使用暗示了對創建對象實例的誤解與綜合房產訪問者相比。 +1閱讀屬性語法的想法。 – 2010-04-07 15:24:50

+0

...以下是參考鏈接:http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/ObjectiveC/Articles/ocProperties.html – jlehr 2010-04-07 16:01:02

+0

開始一種方法通常也是一個壞主意用大寫字母命名,就像你用+ Object方法完成的一樣。 – jlehr 2010-04-07 16:04:53

相關問題