简体   繁体   中英

Array loses all values after go trough its own method - Objective C

I have this piece of code below and I'm trying to add Objects(String elements) to an array, problem is that every time I'm out its adding's method, it goes to nil, it doesn't retain the objects.

I know I'm doing wrong, even that I already tried lot of combinations and variations, even with my own constructor _MyArray etc etc, same result... it works, but not further...

Could you help me please?

@interface ArraysModel()
@property (nonatomic, retain) NSMutableArray *MyArray;
@end

@implementation ArraysModel
@synthesize MyArray;

-(void)AddObjectToTheList:(NSString *)object {

    if(!MyArray) MyArray = [[NSMutableArray alloc] init];
    [MyArray addObject:object];
    NSLog(@"%@",self.MyArray);
    NSLog(@"Object added %u",[self.MyArray count]);
}
-(NSMutableArray *)ObjectList {

    return self.MyArray;
    NSLog(@"%@",self.MyArray);
    NSLog(@"Object added %u",[self.MyArray count]);
}

@end

The header is like this:

@interface ArraysModel : NSObject

-(void)AddObjectToTheList:(NSString *)object;

And here is my call from my ViewController:

- (IBAction)AddToTheList {

    ArraysModel *MyObjectToAdd = [[ArraysModel alloc] init];
    [MyObjectToAdd AddObjectToTheList:TextArea.text];
    [self.view endEditing:YES];

Well, there's your problem -- you're alloc init'ing a new instance of ArraysModel, and therefore a new array with every call. You need to create a strong reference to your instance, and check for whether it exits, and only init if it doesn't.

In the .h:

@property (strong, nonatomic) ArraysModel *myObjectToAdd;

in the .m:

-(IBAction)AddToTheList {
    if (! self.myObjectToAdd) { 
        self.myObjectToAdd = [[ArraysModel alloc] init];
    } 
   [self.myObjectToAdd AddObjectToTheList:TextArea.text]; 
   [self.view endEditing:YES]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM