2013-12-09 83 views
0

所以我想在NSMutableArray中打印用戶。但是這些弦一直沒有出現。從NSMutableArray打印

這裏是我有:

int users = 0; 

- (IBAction)addNewUser:(id)sender { 

    NSString *string; 
    string = userNameTextField.text; 
    [usernameArray insertObject:string atIndex:users]; 
    users++; 
    [self showUsers]; 
} 
-(void)showUsers{ 
    for (int i = 0; i < users; i++){ 
     NSString *s = textView.text; 
     NSString *add; 
     add = [NSString stringWithFormat:@"%@ ",[usernameArray objectAtIndex:i]]; 
     NSString *display = [NSString stringWithFormat:@"%@ \n %@", s, add]; 
     textView.text = display; 
    } 
} 

我也曾嘗試

-(void)showUsers{ 
    for (int i = 1; i < users; i++){ 
     NSString *s = textView.text; 
     NSString *add; 
     add = [usernameArray objectAtIndex:i]; 
     NSString *display = [NSString stringWithFormat:@"%@ \n %@", s, add]; 
     textView.text = display; 
    } 
} 
+0

你確認'textView'和'usernameArray'不是'nil'嗎? – rmaddy

+0

如何查看usernameArray是否爲零? – nfoggia

+0

使用調試器並添加一個'NSLog'語句。 – rmaddy

回答

0

首先,嘗試使用對象更全面的名稱。我正在重寫你的代碼。 問題的常見原因:數組未初始化,您正在開始您的for循環,因爲int i等於1,所以您在可變數組下找不到索引爲0的對象。嘗試下面的代碼。

@interface InterfaceName : InterfaceInherits <IfDelegate> { 
int usersCount; 
NSMutableArray * usernameArray; 

} 

@implementation InterfaceName 
/*There's no more confident way to initialize a variable than in the init method of the class. */ 
-(id)init{ 
usersCount = 0; 
//You have to be sure that your array is not nil 
usernameArray = [NSMutableArray alloc]init]]; 
return self; 
} 
- (IBAction)addNewUser:(id)sender { 
NSString *username = [usernameTextField text]; 
[usernameArray insertObject:username atIndex:usersCount]; 
usersCount++; 

//I'll omit the display as I'm not sure what you were doing with it. 
} 
-(void)showUsers{ 
for (int i = 0; i < usersCount; i++){ 
    NSString *retrievedUser = [usernameArray objectAtIndex:i]; 
    NSString *display = [NSString stringWithFormat:@"User Retrieved : %@",retrievedUser]; 
    textView.text = display; 
} 
} 


    @end