2013-05-09 81 views
0

我只是在學習objective-c。希望這是一個簡單的修復方法,適用於以前曾使用過NSMutableArrays的任何人。開始NSMutableArray - 調試忽略

注意:我在看過3個視頻的同時閱讀了5個文章,然後再問這個問題。有足夠的資源可用於setValue:forKey,但我不相信這適用於此場景。

我想用一個簡單的數組來支持在tic tac toe遊戲中做出的選擇。這個概念很簡單: - 陣列實例化爲9個陣列節點 - 當進行選擇時,當前字母將被放置在相應的陣列節點中 - 檢查遊戲結束的方法將引用陣列節點。

問題: - 我試圖爲每個默認對象設置NSNull值而不是@""。我收到一個錯誤"Unexpected interface name 'NSNull'。 - 調試陣列節點的NSLog邏輯從不執行。我的假設是陣列沒有被填充。


@synthesize lblStatus, currLetter; 
@synthesize selections; 
@synthesize btn0, btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    [selections initWithObjects: 
    @"", @"", @"", @"", @"", @"", @"", @"", @"", nil]; 

    currLetter = @"X"; 
    [self updateTitle]; 
    // Do any additional setup after loading the view, typically from a nib. 
} 

- (IBAction)takeTurn:(id)sender { 
    UIButton *btn = (UIButton *)sender; 
    if (btn.currentTitle == nil) { 
     [selections replaceObjectAtIndex:btn.tag withObject:currLetter]; 
     [sender setTitle:currLetter forState:UIControlStateNormal]; 
     [self changeTurns]; 
    } 
} 

- (void)changeTurns { 

    if ([currLetter isEqualToString:@"X"]) { 
     currLetter = @"O"; 
    } else { 
     currLetter = @"X"; 
    } 

    for (NSString *node in selections) { 
     NSLog([NSString stringWithFormat:@"Node: %@", node]); 
    } 

    [self updateTitle]; 
} 

- (void)updateTitle { 
    [lblStatus setText:[NSString stringWithFormat:@"%@'s Turn", currLetter]]; 
} 

如果你看到別的被認爲是「不好的代碼」,我會很樂意採取這種反饋也。

任何幫助,非常感謝。

+1

決不叫'-init'方法,無需先調用'+ alloc',像這樣:'[[美孚ALLOC] INIT]'。 – Caleb 2013-05-09 13:48:22

回答

1

代替[selections initWithObjects: @"", @"", @"", @"", @"", @"", @"", @"", @"", nil];

寫入selections = [[NSMutableArray alloc] initWithObjects: @"", @"", @"", @"", @"", @"", @"", @"", @"", nil];

+0

工作完美!非常感謝您的快速響應。 – alockrem 2013-05-09 13:37:44

+0

不客氣,好友 – 2013-05-09 13:38:21

-1

嘗試增加[NSNull空]到該陣列。您可以在陣列內添加空對象,而不是空字符串的

問候

+1

你預計這會產生什麼不同,爲什麼? – Caleb 2013-05-09 13:49:23

+0

點擊相同的按鈕將保持轉變。還需要添加一個驗證。如果在用戶點擊按鈕時在數組內添加空對象,請檢查該對象是否爲類[NSNull類]。如果不是,請不要改變轉彎並讓用戶選擇或繼續您的實施 – Arun 2013-05-10 05:35:29

+1

我很欣賞反饋,並且我同意NSNull是我最初想要使用的方法。儘管如此,該軟件並沒有如你所描述的那樣反應。一旦標題已應用(X或O),輕擊同一個按鈕將被忽略。 – alockrem 2013-05-10 14:41:12