I have three button named(titled) hello, nothing, heaven and one label (IBOutlet UIlabel lab). I want to display three diff messages for three diff button click. But the following code failed to accomplish this. Can anyone suggest any idea?
-(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];
}
output:
warning:unused variable str;
The problem is that in each ‘then’ clause of the various
ifstatements, you’re creating a new local variable namedstr, assigning it to a new string, and then the variable goes out of scope. The compiler warning should tick you off to this: you’re writing to a variable but never reading from it.Ordinarily, your code wouldn’t compile, but you apparently have another variable named
strin scope later on. Your new definitions ofstrare shadowing the old one: while the new namestris in scope, the namestrrefers to that variable, not the outer one, and the outer one is cannot be referred to.The solution is to move the declaration of
strup to the top of the function. Furthermore, it’s simpler just to use[NSString stringWithFormat:@"blah"]instead of[[NSString alloc] initWithFormat:@"blah"], since the former gives you an autoreleased object. This saves you from having to manuallyreleaseit later on. Note that assigninglab.text=strretains it, since thetextproperty of theUILabelclass has theretainmodifier.Also note that with your original code, you had both a memory leak and memory corruption — since you were allocating a string and then losing a reference to it (by the new local variable
strgoing out of scope) without releasing it, and then you were callingreleasean extra time on whatever the outerstrvariable was. Moving thestrdeclaration to the top of the function fixes both problems.I’m also assuming that your format strings are more complicated than just plain strings. If you’re actually assigning constant strings such as
"abc", then of course it’s much simpler to just dostr=@"abc"instead ofstr=[NSString stringWithFormat:@"abc"].