2011-11-03 55 views
2

如何在更新後訪問@public NSArrayNSMutableArray?從一個班級到另一個班級?可可:訪問@public NSArray將其從一個類更新到另一個類

我可以通過調用-(id)init來訪問它..當程序啓動時,但如果我想稍後更新它,我會得到零。有什麼問題?

簡單示例代碼:

MyFirstClass.h

#import <Foundation/Foundation.h> 

@interface MyFirstClass : NSObject 
{ 
@public 

    NSArray *testArray; 

} 

-(IBAction)Button:(id)sender; 

@end 

MyFirstClass.m

#import "MyFirstClass.h" 

@implementation MyFirstClass 
- (id)init { 
if (self = [super init]) { 

    //I can take this Array from here 

    //testArray = [NSArray arrayWithObjects: @"first", @"second", @"third", nil]; 

} 
    return self; 
} 

-(IBAction)Button:(id)sender { 

    //How take this Array? 

    testArray = [NSArray arrayWithObjects: @"first", @"second", @"third", nil]; 

} 

@end 

SimpleClass.h

#import <Foundation/Foundation.h> 
#import "MyFirstClass.h" 

@interface SimpleClass : NSObject 
{ 
    MyFirstClass *other; 
} 

-(IBAction)ButtonGet:(id)sender; 

@end 

SimpleClass.m

#import "SimpleClass.h" 
#import "MyFirstClass.h" 

@implementation SimpleClass 

-(IBAction)ButtonGet:(id)sender { 

    other = [[MyFirstClass alloc] init];  

    if(other->testArray) { 
     NSLog(@"Working!"); 
    } 
    else { NSLog(@"Not working!"); } 

} 

@end 

創建的示例在* .xib中有兩個按鈕。一個名爲「Button」(MyFirstClass)和其他「ButtonGet」(SimpleClass)的按鈕。所以當程序開始時需要按「Button」然後「ButtonGet」,之後NSLog應該寫「Working!」如果它得到testArray,如果沒有 - 「不工作!」。它總是顯示「不工作!」。

+0

請編輯您的問題,併發布代碼,您聲明實例變量,爲其分配一個數組實例,並在其中嘗試使用它。另外,您是否使用垃圾回收,ARC或手動內存管理? – 2011-11-03 23:49:53

+0

感謝您的評論,我沒有使用垃圾回收,我正在使用手動內存管理。 –

+0

在'awakeFromNib'中放置一個斷點,然後在調試器面板中右鍵單擊'testArray'並選擇「Watch Variable」。這樣,下次你的變量被修改,調試器會暫停你的程序。 – zneak

回答

3

歡迎來到Objective C!如果您感到不知所措,並希望閱讀一些介紹性資料,請查看Peter Hosey的優秀"Useful Cocoa/Cocoa Touch Links" card中的鏈接。

您在-[SimpleClass ButtonGet:]創建MyFirstClass實例,因爲它的testArray成員未明確分配給-[MyFirstClass init],它是(正確)初始化爲零。它將永遠保持這種方式,除非你指定了別的東西,但你永遠不會這樣做。 (您只能分配給它的[MyFirstClass Button:],但你永遠不調用該方法。)

其他的事情要考慮:

  • 手冊內存管理,您需要知道Cocoa memory management rules不斷銘記在心,而寫你的代碼。例如,當您將其分配給成員變量時,需要保留+[NSArray arrayWithObjects:]的結果,並在-[MyFirstClass dealloc]中將其釋放。同樣,您需要釋放-[SimpleClass dealloc]中的other對象。

  • 使用屬性(使用@property聲明)而不是直接引用另一個類的成員變量要簡潔得多。

  • 請考慮遵循Cocoa Coding Guidelines並以小寫字母開始您的方法名稱。它使您的代碼更適合系統API,並且使其他人更容易閱讀。

+0

非常感謝您的回答。你是什​​麼意思,說「分配別的東西」,你可以給我舉例說明如何做到這一點?按下按鈕時我會調用它,不是嗎? –

+0

你用賦值操作符('=')給某個成員變量賦值 - 你已經編寫了代碼在' - [MyFirstClass Button:]'中做了這個。不過,您的示例中並未實際執行該代碼。爲了調用這個方法,你可以(例如)在創建MyFirstClass對象之後,在你檢查testArray之前,在' - [SimpleClass ButtonGet]'中插入語句'[other Button:nil]有沒有按鈕?你沒有提到你的問題中的任何按鈕。 –

+0

有兩個按鈕 - (IBAction)按鈕和 - (IBAction)ButtonGet:,對不起,我沒有提到。所以我按「按鈕」按鈕時執行此代碼,不是?並從其他類按鈕「ButtonGet」 –