gpt4 book ai didi

iPhone(iOS): copying files from main bundle to documents folder causes crash

转载 作者:行者123 更新时间:2023-12-03 18:23:11 24 4
gpt4 key购买 nike

我正在尝试设置我的应用程序,以便在首次启动时,位于主包中“Populator”文件夹中的一系列文件被复制到文档目录中。

我当前的实现如下:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Populator"];
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:@"Files"];
NSLog(@"Source Path: %@\n Documents Path: %@ \n Folder Path: %@", sourcePath, documentsDirectory, folderPath);

NSError *error;

[[NSFileManager defaultManager] copyItemAtPath:sourcePath
toPath:folderPath
error:&error];

NSLog(@"Error description-%@ \n", [error localizedDescription]);
NSLog(@"Error reason-%@", [error localizedFailureReason]);
....
return YES;
}

但是,第一次运行时会崩溃,并显示以下控制台消息(但文件已复制)。下次打开应用程序时,它不会崩溃。

    2010-07-13 15:14:26.418 AppName[5201:207] Source Path: /Users/jack/Library/Application Support/iPhone Simulator/3.2/Applications/1076C1FA-60B0-4AC7-8CD4-74F81472DAE6/AppName.app/Populator
Documents Path: /Users/jack/Library/Application Support/iPhone Simulator/3.2/Applications/1076C1FA-60B0-4AC7-8CD4-74F81472DAE6/Documents
Folder Path: /Users/jack/Library/Application Support/iPhone Simulator/3.2/Applications/1076C1FA-60B0-4AC7-8CD4-74F81472DAE6/Documents/Files
2010-07-13 15:14:26.466 AppName[5201:207] *** +[AppNameAppDelegate localizedDescription]: unrecognized selector sent to class 0xa79c
2010-07-13 15:14:26.475 AppName[5201:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[AppNameAppDelegate localizedDescription]: unrecognized selector sent to class 0xa79c'
2010-07-13 15:14:26.495 AppName[5201:207] Stack: (
40911435,
2569270537,
41183227,
40645910,
40642578,
9142,
2815466,
2819475,
2844680,
2826401,
2858055,
49271164,
40452156,
40448072,
2817668,
2850273,
8776,
8630
)

有人对出了什么问题有什么建议吗?我已经设置了一些代码来实现“仅在首次启动时”功能,但为了清楚起见,没有将其包含在此处。

谢谢

最佳答案

   NSError *error;

您正在声明一个局部变量而不对其进行初始化。因此,它会充满垃圾。

  [[NSFileManager defaultManager] copyItemAtPath:sourcePath 
toPath:folderPath
error:&error];

如果该行没有发生错误,则仍然保持error的垃圾状态。

  NSLog(@"Error description-%@ \n", [error localizedDescription]);

现在您将消息发送到某个随机的、未初始化的位置。这就是崩溃的根源。

<小时/>

为避免这种情况,请将 error 初始化为 nil

NSError* error = nil;
// ^^^^^

或者仅当 -copyItemAtPath:... 返回 NO 时才打印错误(其中正确填充了 error)。

if (![[NSFileManager defaultManager] copyItemAtPath:sourcePath ...]) {
NSLog(...);
}

关于iPhone(iOS): copying files from main bundle to documents folder causes crash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3238143/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com