所以我想在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 :(得分:0)
首先尝试为对象使用更全面的名称。我正在重写你的代码。 问题的常见原因:数组未初始化,您正在使用int i等于1开始 for循环,因此您在可变数组中缺少索引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