开发者

Image not set on the custom button

I have two views.On my 1st view i have one custom button.By clicking on that button the other view will create with Icon library.by clicking on that icon the icon will set to the 1st开发者_运维技巧 view.i have store the value into NSUser defaults.but the icon is not set.

here is the code:

view2:

 -(IBAction)btnImage1Clicked:(id)sender{

NSString *img1=@"NODE - BOOK_a.png";
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

if (standardUserDefaults) {

    [standardUserDefaults setValue:img1 forKey:@"image1"];
    [standardUserDefaults synchronize];
}
  [img1 release];


[self dismissModalViewControllerAnimated:YES];

}

view1:

-(void)viewWillAppear:(BOOL)animated{

NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

NSString *val = nil;
NSLog(@"val=%@",val);
NSLog(@"user default=%@",[standardUserDefaults valueForKey:@"image1"]);
if (standardUserDefaults) 
    val = [standardUserDefaults stringForKey:@"image1"];
NSLog(@"image name=%@",val);

UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",val]];
 stringWithFormat:@"%@",val]] forState:UIControlStateNormal]; 
[imageButton setBackgroundImage:image forState:UIControlStateNormal]; 

forState:UIControlStateNormal]; 
[[NSUserDefaults standardUserDefaults] setValue:@"" forKey:@"image1"];

}


I think may be Maulik's code is working but I dont think it is a right way to use setObject:forKey method for NSString.

There is a basic mistake in the code.

You are allocating string value to img1 assigning it to the NSUserDefaults and then releasing the string ultimately that even releases the string in NSUserDefaults as it is not copied.

Is there any reason for releasing img1 in view2 when you are not allocating it? Overreleasing is not a good practice. It may lead to crash because of Zombies at some point in time.

So put the code in your view2 as shown below. i.e. remove the [img1 release] statement and it should work fine with your code:

-(IBAction)btnImage1Clicked:(id)sender
{

     NSString *img1=@"NODE - BOOK_a.png";
     NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

     if (standardUserDefaults) {

        [standardUserDefaults setValue:img1 forKey:@"image1"];
        [standardUserDefaults synchronize];
     }

    [self dismissModalViewControllerAnimated:YES];
}

So the bottom line is you don't need to release img1 when you are not allocating it.

For more information on memory management, you may refer to Memory Management Guidelines

Hope this helps you.


to set string in NSUserDefaults try this.

NSString *valueToSave = @"someValue";
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

[standardUserDefaults setObject:img1 forKey:@"image1"];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜