【问题标题】:writeToFile always crashes with stringByAppendingPathComponentwriteToFile 总是与 stringByAppendingPathComponent 崩溃
【发布时间】:2011-06-01 08:46:21
【问题描述】:

我在这个问题上坐了几个小时,现在我瞎了。 ;-)

我这里有这段代码:

- (id) initWithImage:(UIImageView*)imageView andPath: (NSString*) path{

   [super init];
   drawImage = imageView;
   imageFilePath = [NSString stringWithString: path];
   NSLog(@"fath: %@", imageFilePath);
   return self;
}

    NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(drawImage.image)];   
    NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *path = [docsDirectory stringByAppendingPathComponent:@"img.data"];
    NSLog(@"path: %@", path);
    [imageData writeToFile:path atomically:YES];

此代码有效,但当我更改时
[imageData writeToFile:path atomically:YES];

[imageData writeToFile:imageFilePath atomically:YES];
应用程序崩溃。
但是字符串看起来完全一样:

2011-06-01 10:38:10.178 L3T[3756:207] fath: /Users/max/Library/Application Support/iPhone Simulator/4.3/Applications/A73945CF-9FD0-46E9-A16B-9C0EFC924B0F/Documents/img.data
2011-06-01 10:38:11.864 L3T[3756:207] path: /Users/max/Library/Application Support/iPhone Simulator/4.3/Applications/A73945CF-9FD0-46E9-A16B-9C0EFC924B0F/Documents/img.data

我就是不明白!

【问题讨论】:

  • imageFilePath的定义在哪里?它是您班级中的成员变量吗? imageFilePath 何时分配和初始化?

标签: iphone objective-c writetofile


【解决方案1】:

代码imageFilePath = [NSString stringWithString: path]; 为您提供了一个您不拥有的对象,因此您不能依赖它稍后在您的代码中可用。将其更改为:

imageFilePath = [[NSString alloc] initWithString: path];

你应该没事的。

【讨论】:

  • 对。 [NSString stringWithString: 路径];返回一个自动释放对象。因此,当您尝试访问 imageFilePath 时,它已经(自动)释放了。
  • @prat +stringWithString: 不一定返回自动释放的对象。更准确的说法是它返回一个不属于调用者的对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-15
相关资源
最近更新 更多