我正在开发一个应用程序,它从位于我的网络服务器上的plist中检索其数据。因此,应用程序依赖于网络连接。我希望用户能够在离线时使用我的应用程序,因此每次应用程序加载网络连接时,我都会在用户设备上保存plist的副本。从那里,我从位于设备上的plist中读取数据。
但是,我遇到了麻烦。我开始在AppDelegate的didFinishLaunchingWithOptions
方法中下载数据。这是这样做的:
if(hasConnection) { // returns TRUE or FALSE based on Apple's example on checking network reachability
NSLog(@"Starting download of data.");
// loading using NSURLConnection
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:FETCH_URL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
receivedData = [[NSMutableData data] retain];
}
}
然后我将数据添加到Bands.plist
connectionDidFinishLoading
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// throw data into a property list (plist)
NSMutableArray *tmpArray = [NSPropertyListSerialization propertyListFromData:receivedData mutabilityOption:NSPropertyListMutableContainers format:nil errorDescription:nil];
NSMutableArray *plistArray = [[NSMutableArray alloc] initWithArray:tmpArray];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Bands.plist"];
[plistArray writeToFile:path atomically:YES];
[plistArray release];
// release the connection, and the data object
[connection release];
[receivedData release];
}
但是第一次加载应用程序时,它会崩溃。我相信这是由于应用程序尝试访问此数据,即使它尚未保存。如果我删除试图访问本地保存的数据的部分,我没有问题。如果我再次添加它并重新启动应用程序(第二次加载),我也不会遇到问题。
有没有人知道如何解决这个问题?
就好像我的应用程序试图加载和处理尚不存在的数据一样。
答案 0 :(得分:0)
首先尝试检查plist是否存在:
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
... // read the data, etc.
}
else {
... // don't try to read it
}
干杯,
的Sascha