【问题标题】:How to Pass NSString Value to Another Property in Objective-C如何将 NSString 值传递给 Objective-C 中的另一个属性
【发布时间】:2012-09-15 14:35:30
【问题描述】:

基本上,我有这个 if 语句:

NSString *loginResult = [resultsArray valueForKey:@"statusMsg"];
if ([loginResult isEqualToString:@"success"])
{
    [self successDialog]; // Success
}
else 
{
    [self failedDialog]; // Failed
}

如果成功,这是解析后的 JSON:

{"results":{"statusMsg":"success"}}

如果失败,解析的 JSON 会有所不同:

{"results":{"statusMsg":"password incorrect."}}

我想将 statusMsg 键返回的字符串值传递给 failedDialog 方法内的警报视图。 failedDialog方法定义为:

- (void)failedDialog:(NSString *)errorMessage
{
    UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:kRegFailed
                                                     message:errorMessage
                                                    delegate:self
                                           cancelButtonTitle:kOK
                                           otherButtonTitles:nil, nil];
    dialog.tag = 2;
    [dialog show];  
}

我该怎么做才能让警报视图返回错误消息。蒂亚!

【问题讨论】:

    标签: objective-c xcode methods nsstring


    【解决方案1】:

    如果你的 resultsArray 是 NSArray 对象,不知道为什么要这样做

    NSString *loginResult = [resultsArray valueForKey:@"statusMsg"];
    

    把它放在你的头文件中

    - (void)failedDialog:(NSString *)errorMessage;
    

    试试这个,假设你的 jsonDict = { "results" :{ "statusMsg" : "password wrong." } }

    [self failedDialog:[NSString stringWithString:[[jsonDict objectForKey:@"results"]objectForKey:@"statusMsg"]]];
    

    【讨论】:

    • 我想要的是 failedDialog 接收消息而不是 successDialog。
    • 对不起,我编辑了答案,只是更改了方法名称..看看
    • 我有这个警告:找不到实例方法'-failedDialog:'(返回类型默认为'id')
    • 警告是什么? resultsArray 是数组还是字典?
    • 把它放在你的头文件.h文件中 - (void)failedDialog:(NSString *)errorMessage;回答编辑检查它
    【解决方案2】:

    编辑

    NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    
    NSString *loginResult = [[jsonDictionary objectForKey:@"results"] objectForKey:@"statusMsg"];
    if ([loginResult isEqualToString:@"success"])
    {
        [self successDialog]; // Success
    }
    else 
    {
        [self failedDialog:loginResult]; // Failed
    }
    

    【讨论】:

    • 这是我想要的,但它返回一个警告。
    • 我实现了头文件更改并且它起作用了。我接受了 Neo 的回答,因为这让我实现了我想要实现的目标。
    猜你喜欢
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-14
    相关资源
    最近更新 更多