如何在目标c中将对象添加到现有数组

时间:2013-12-26 13:01:17

标签: objective-c cocoa nsmutablearray

我是目标c的新手,并且对nsmutableArray有一些问题。我的gui上有按钮和两个文本字段,我希望当我点击按钮时,文本字段中的字符串应该添加到我现有的数组中。但问题是,当我点击按钮时,它总是创建新的数组。帮助任何人。

myfile.m中的按钮代码如下:

NSMutableArray* myArray = [NSMutableArray array];
NSString *strr=[textf stringValue];
NSString *strr1=[textf1 stringValue];
// [myArray addObject:strr]; // same with float values
// [myArray addObject:strr1];
[myArray addObject:strr];
[myArray addObject:strr1];
int i,j=0;
int count;
for (i = 0, count = [myArray count]; i < count; ){
    NSString *element = [myArray objectAtIndex:i];
    NSLog(@"The element at index %d in the array is: %@", i, element); 
}

1 个答案:

答案 0 :(得分:2)

因为你总是在这一行创建新数组:
NSMutableArray* myArray = [NSMutableArray array];

将您的数组作为类对象的属性。例如:

@interface MyClass ()
@property (nonatomic, strong) NSMutableArray * array;
@end

@implementation MyClass

- (id)init {
    self = [super init];
    if ( self ) {
        _array = [NSMutableArray array];
    }
    return self;
}

- (IBAction)onButtonClick {
    NSString *strr = [textf stringValue];
    NSString *strr1 = [textf1 stringValue];

    [self.array addObject:strr];
    [self.array addObject:strr1];

    for ( int i = 0; i < [myArray count]; i++ ) {
        NSString * element = [myArray objectAtIndex:i];
        NSLog(@"The element at index %d in the array is: %@", i, element); 
    }
}

@end