自定义对象初始化不会使用addObject存储NSMutableArray对象:

时间:2014-04-26 23:58:28

标签: ios objective-c nsmutablearray init

在创建具有静态登录的登录屏幕时,我试图将它们私下存储在以下类实现中。当按钮创建IONServer个对象时,我使用函数-(void)login:(NSString *)username password:(NSString *)pw对其进行初始化,并将其传递给两个UITextField.text个字符串。

如果您在init中注意到我正在使用NSLog测试内容,但在每个断点处,storedLogins NSMutable数组似乎都是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 个答案:

答案 0 :(得分:1)

您需要初始化数组:

-(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;

}