2011-06-01 31 views
0

我在這個問題上坐了幾個小時,現在我已經失明瞭。 ;-)writeToFile總是與stringByAppendingPathComponent一起崩潰

我有這樣的代碼在這裏:

- (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 

我只是不明白了!

+0

imageFilePath的定義在哪裏?它是你班級中的一員嗎? imageFilePath何時分配並初始化? – 2011-06-01 08:48:53

回答

3

代碼imageFilePath = [NSString stringWithString: path];爲您提供了一個您不擁有的對象,因此您不能依賴它在稍後的代碼中可用。更改爲:

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

你應該沒問題。

+0

沒錯。 [NSString stringWithString:path];返回一個autorelease對象。所以當你試圖訪問imageFilePath時,它已經被(自動)釋放。 – 2011-06-01 09:09:34

+1

@prat'+ stringWithString:'不一定會返回一個自動釋放對象。更準確地說,它返回一個不屬於調用者的對象。 – 2011-06-01 09:12:47

+0

謝謝!使我的一天;-) – madmax 2011-06-01 09:24:12