Hãy xem xét hai mẫu đoạn mã sau:Tại sao lại sử dụng NSFileManager thay vì chỉ sử dụng phương thức writeToFile của NSData: phương pháp: khi tạo một tệp mới?
NSData *imgData = UIImagePNGRepresentation(imgFull);
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"itemImg_%i.png", timestamp]]; //add our image to the path
[imgData writeToFile:fullPath atomically:YES];
và
NSData *imgData = UIImagePNGRepresentation(imgFull);
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"itemImg_%i.png", timestamp]]; //add our image to the path
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createFileAtPath:fullPath contents:imgData attributes:nil];
Ví dụ thứ hai đòi hỏi thêm một dòng mã và khởi tạo của một đối tượng NSFileManager, trong khi ví dụ đầu tiên chỉ đơn giản là có đối tượng NSData imgData
tự ghi vào một tệp. Một lợi thế bổ sung của ví dụ đầu tiên là nó có thể ghi đè lên một tệp đã tồn tại từ trước có cùng tên.
Câu hỏi của tôi là: khi tạo tệp mới, trong trường hợp nào bạn thực sự muốn sử dụng NSFileManager và phương thức của nó createFileAtPath:contents:attributes:
?
WriteToFile của NSData không ghi đè như mặc định, từ trải nghiệm của tôi. Và cũng không phải của hàm createFileAtPath của NSFileManager với các thuộc tính: nil.Thông tin về các thuộc tính NSDictionary phương pháp là sắp tới, cho thấy rằng nó không thường được sử dụng. –