2011-08-22 73 views
1

請看下面的代碼。如何從另一個類設置NSString *屬性?

FirstViewController.h:

@interface FirstViewController : UIViewController { 
    NSString* inputData; 
} 

@property (nonatomic, copy/retain) NSString* inputData; 

FirstViewController.m:

@synthesize inputData; 

SecondViewController.m:

- (IBAction)buttonSaveDown { 
    [firstViewController setInputData:@"Text"]; 
    firstViewController.inputData = @"Text"; 
    firstViewController.inputData = [[NSString stringWithString:@"Text"] retain]; 
} 

與inputData每一行後面添加斷點。檢查firstViewController.inputData - 它是'(null)'!爲什麼?

Printing description of inputData: 
(null) 

另外我嘗試在編輯器中編輯值。設置值後,結果也爲'(null)'。

構建中沒有任何警告。請幫助任何人。非常感謝!

給版主:對不起,有人刪除了同一個前面的問題,當我要求刪除它的所有評論。

+1

FirstViewController是否已初始化?同樣在你設置inputData的第三次嘗試中,如果@property指令被設置爲複製或保留,則不需要保留調用,這實際上會導致內存泄漏。 –

+3

您確定firstViewController在buttonSaveDown方法中有效嗎?如果它爲零,那麼這些都不會起作用。 – Flyingdiver

回答

3

firstViewController變量沒有設置任何東西。您需要將其設置爲FirstViewController的有效實例,然後才能對其執行任何有用的操作。

1

只需使用

@property (nonatomic, retain) NSString* inputData; 

然後將這些各應工作:

[firstViewController setInputData:@"Text"]; 
firstViewController.inputData = @"Text"; 
firstViewController.inputData = [NSString stringWithString:@"Text"]; 
+0

不要幫助。 inputData:'(null)'。對不起,但這是不正確的答案。 – Dmitry

+1

無論如何,就我所知,'copy/retain'是一種無效的語法。選擇其中一個。請參閱http://stackoverflow.com/questions/387959/nsstring-property-copy-or-retain關於哪些建議。 –

相關問題