0

我正在尝试打印(nslog)嵌入在我创建的 PhotoView 对象中的照片的名称。我创建了 2 个视图控制器类和扩展 UIButton 类的 PhotoView 类,以在以前的视图控制器之一中填充网格。

在 PhotoView.h 我有

@interface PhotoView : UIButton
@property (assign, nonatomic) NSString *photoName;
...

在 PhotoView.m 我有

    self.tag = [[data objectForKey:@"PhotoID"] intValue];
    self.photoName = [data objectForKey:@"PhotoName"];

在同一个文件上打印出 tag 和 photoName 的值后,一切看起来都很好。

单击 PhotoView 后尝试从另一个类打印 photoName 的值时出现问题

-(void)didSelectPhoto:(PhotoView*)sender
{   
    NSLog(@"%@", [NSString stringWithFormat:@"%@", sender.photoName]);
}

单击 photoView 后,出现 EXC_BAD_ACCESS 错误。

但是,如果我这样做

NSLog(@"%@",[NSNumber numberWithInt:sender.tag]])

我没有收到此错误。

什么可能是错的?

提前致谢。

4

1 回答 1

2

两个备注:

  1. [NSString stringWithFormat:@"%@", sender.photoName] - No please! No! Don't do that! It's not only superfluous and wastes CPU cycles, but it also heavily decreases readability. if you have a string, you don't have to duplicate it like this, just use the string object directly:

NSLog(@"%@", sender.photoName);
  1. The actual error you have is this:

@property (assign, nonatomic) NSString *photoName;

I. e. you have an assign property, so it doesn't retain its value. When your string object goes out of scope, it's deallocated (and since it's not weak, it isn't automatically set to nil, but it holds whatever garbage value that invalid pointer is, hence the crash). Write instead

@property (retain, nonatomic) NSString *photoName;

if you're not using ARC, and

@property (strong, nonatomic) NSString *photoName;

if you are.

于 2013-01-14T21:57:04.560 回答