Custom Object Initialization does not store NSMutableArray objects with addObject:

两盒软妹~` 提交于 2019-12-12 01:31:40

问题


In creating a login screen with static logins I'm trying to store them privately in the following class implementation. When a button creates IONServer objects I initialize it with the function -(void)login:(NSString *)username password:(NSString *)pw and pass it two UITextField.text strings.

If you notice in the init I am testing stuff with NSLog but at every breakpoint it seems like the storedLogins NSMutable array is nil.

IONServer.m

#import "IONServer.h"
#import "IONLoginResult.h"

@interface IONServer ()

@property (nonatomic) NSMutableArray *storedLogins;

@end

@implementation IONServer

-(void)createStoredLogins
{
    NSArray *firstUser = @[@"user1",@"pass1"];
    NSArray *secondUser = @[@"user2",@"pass2"];

    [self.storedLogins addObject:firstUser];
    [self.storedLogins addObject:secondUser];

}

-(instancetype)init {
    self = [super init];

    if (self) {
        [self createStoredLogins];
        NSLog(@"Stored logins: %@", _storedLogins);
        NSLog(@"Stored user: %@", _storedLogins[0][0]);
    }
    return self;

}

-(void)login:(NSString *)username password:(NSString *)pw
{
    NSArray *logins = [[NSArray alloc]initWithArray:_storedLogins];

    for (int i = 0; i < [logins count]; i++) {
        if (username == logins[i][0] && pw == logins[i][1]) {
            IONLoginResult *result = [[IONLoginResult alloc] initWithResult:YES errorMessage:@"Success!"];
            self.result = result;
            break;
        } else {
            IONLoginResult *result = [[IONLoginResult alloc] initWithResult:NO errorMessage:@"Error!"];
            self.result = result;
        }
    }
}

-(void)logout
{

}

@end

回答1:


You need to initialize the array:

-(instancetype)init {
    self = [super init];

    if (self) {
        _storedLogins = [[NSMutableArray alloc] init];
        [self createStoredLogins];
        NSLog(@"Stored logins: %@", _storedLogins);
        NSLog(@"Stored user: %@", _storedLogins[0][0]);
    }
    return self;

}


来源:https://stackoverflow.com/questions/23317855/custom-object-initialization-does-not-store-nsmutablearray-objects-with-addobjec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!