Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 目标NSC字符串比较_Objective C - Fatal编程技术网

Objective c 目标NSC字符串比较

Objective c 目标NSC字符串比较,objective-c,Objective C,我有三个按钮名为(标题为)hello,nothing,heaven和一个标签(IBLabel lab)。我想为三个差异按钮单击显示三个差异消息。但是下面的代码未能实现这一点。有人能提出什么建议吗 -(IBAction)buttonclick:(id)sender { NSString *title=[sender titleForState:UIControlStateNormal]; if([title isEqualToString:@"hello"])

我有三个按钮名为(标题为)hello,nothing,heaven和一个标签(IBLabel lab)。我想为三个差异按钮单击显示三个差异消息。但是下面的代码未能实现这一点。有人能提出什么建议吗

-(IBAction)buttonclick:(id)sender  
{  

    NSString *title=[sender titleForState:UIControlStateNormal];

    if([title isEqualToString:@"hello"])
    {

        NSString *str=[[NSString alloc] initWithFormat:@"abc"];
    }
    else if([title isEqualToString:@"nothing"]) {

        NSString *str=[[NSString alloc] initWithFormat:@"def"];
    }
    else if([title isEqualToString:@"heaven"])
    {

        NSString *str=[[NSString alloc] initWithFormat:@"ijk"];
    }   

    lab.text=str;
    [str release];
}
输出:

warning:unused variable str;  

不要使用按钮的标题来区分按钮。如果你的按钮是本地化的,那就不行了。可以使用不同的操作,也可以使用标记来区分它们

警告是你在这种情况下做错了什么的线索。局部变量仅在其声明的范围内可见,因此您的lab.text=str行实际上是将lab.text设置为在别处定义的str,即静态变量或实例变量。以下是您可以做的:

NSString *str;

switch ([sender tag]) {
  case FirstButtonTag:
    str = @"abc";
    break;
  case SecondButtonTag:
    str = @"def";
    break;
  case ThirdButtonTag:
    str = @"ijk";
    break;
}

lab.text = str;

问题是,在各种
if
语句的每个'then'子句中,您正在创建一个名为
str
的新局部变量,并将其分配给一个新字符串,然后该变量超出范围。编译器警告应该提醒您:您正在写入变量,但从未从中读取

通常情况下,您的代码不会编译,但很明显,稍后在作用域中还有另一个名为
str
的变量。您对
str
的新定义覆盖了旧定义:当新名称
str
在范围内时,名称
str
引用了该变量,而不是外部变量,外部变量无法引用

解决方案是将
str的声明上移到函数的顶部。此外,使用
[nsstringwithformat:@“blah”]
而不是
[[NSString alloc]initWithFormat:@“blah”]
更简单,因为前者提供了一个自动删除的对象。这样您就不必在以后手动
释放它了。请注意,分配
lab.text=str
会保留它,因为
UILabel
类的
text
属性具有
retain
修饰符

-(IBAction)buttonclick:(id)sender  
{  
    NSString *title=[sender titleForState:UIControlStateNormal];
    NSString *str;

    if([title isEqualToString:@"hello"])
    {
        str=[NSString stringWithFormat:@"abc"];
    }
    else if([title isEqualToString:@"nothing"])
    {
        str=[NSString stringWithFormat:@"def"];
    }
    else if([title isEqualToString:@"heaven"])
    {
        str=[NSString stringWithFormat:@"ijk"];
    }

    lab.text=str;
}
还要注意的是,在原始代码中,内存泄漏和内存损坏——因为您分配了一个字符串,然后失去了对它的引用(通过新的局部变量
str
超出范围),而没有释放它,然后,您对外部
str
变量调用了
release
一段额外的时间。将
str
声明移到函数顶部可以解决这两个问题

我还假设格式字符串比普通字符串更复杂。如果您实际分配的是常量字符串,例如
“abc”
,那么只需执行
str=@“abc”
,而不是
str=[NSString stringWithFormat:@“abc”]