2013-05-18 80 views
0

我試圖填充或種子我的應用程序的某些項目,使用下一個方法,這就是所謂的didFinishLaunchingWithOptions方法播種與項目的應用程序:的iOS:從plist中

-(void)seedItems { 
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults]; 
    if (![ud boolForKey:@"MUserDefaultsSeedItems"]) { 
     // Load seed items 
     NSString *filePath = [[NSBundle mainBundle] pathForResource:@"seed" ofType:@"plist"]; 
     NSArray *seedItems = [NSArray arrayWithContentsOfFile:filePath]; 
     NSMutableArray *items = [NSMutableArray array]; 
     for (int i = 0; i < [seedItems count]; i++) { 
      NSDictionary *seedItem = [items objectAtIndex:i]; 
      MShoppingItem *shoppingItem = [MShoppingItem createShoppingItemWithName:[seedItem objectForKey:@"name"] andPrice:[[seedItem objectForKey:@"price"] floatValue]]; 
      [items addObject:shoppingItem]; 
     } 

     // Items path 
     NSString *itemsPath = [[self documentsDirectory] stringByAppendingPathComponent:@"items.plist"]; 

     // Write to file 
     if ([NSKeyedArchiver archiveRootObject:items toFile:itemsPath]) { 
      [ud setBool:YES forKey:@"MUserDefaultsSeedItems"]; 
     } 
    } 
} 

文件seed.plist有以下內容:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> 
<plist version="1.0"> 
<array> 
    <dict> 
     <key>name</key> 
     <string>Naranjas</string> 
     <key>price</key> 
     <integer>0</integer> 
    </dict> 
    <dict> 
     <key>name</key> 
     <string>Peras</string> 
     <key>price</key> 
     <integer>0</integer> 
    </dict> 
    <dict> 
     <key>name</key> 
     <string>Manzanas</string> 
     <key>price</key> 
     <integer>0</integer> 
    </dict> 
</array> 
</plist> 

的問題是,這樣做NSArray *seedItems = [NSArray arrayWithContentsOfFile:filePath];時,它說,數組包含3個對象,但他們Out of scopeSummary Unavailable

有什麼想法嗎?

非常感謝!

回答

0

在擁有filePath之後,請使用NSFileManager檢查它是否存在。如果它不存在,請檢查文件是否已正確添加到Xcode中,並將其設置爲應用目標的一部分,以便它出現在「複製捆綁軟件資源」構建階段。您可以通過在Xcode中選擇種子文件並查看實用程序檢查器中的「目標成員資格」來檢查目標成員資格。

對問題的更新表明數組已加載,但在調試器中列出爲不可用。這表明該數組已被釋放(因爲它不再被使用)。這表明一個錯字。在代碼仔細看,我看到:

NSDictionary *seedItem = [items objectAtIndex:i]; 

這也許應該是:

NSDictionary *seedItem = [seedItems objectAtIndex:i]; 

我猜你以前看到的崩潰?

+0

以及該文件存在,我也檢查了目標會員資格和所有複製包資源和一切都好 – noloman

+0

非常感謝,這正是這個問題。我對這些名字感到困惑。乾杯! – noloman