Search code examples
iosobjective-cnsarrayplistnscollectionview

How can i create a plist file from these arrays?


I have a NSCollectionView that can read data like this code:

    self.contents = @[
                  @{@"itemTitle":@"Product 1",
                    @"itemPrice":@"$20.90",
                    @"itemImage":@"PastedGraphic-1.png"},

                  @{@"itemTitle":@"Product 2",
                    @"itemPrice":@"$10.90",
                    @"itemImage":@"PastedGraphic-3.png"},

                  @{@"itemTitle":@"Product 3",
                    @"itemPrice":@"$9810.90",
                    @"itemImage":@"PastedGraphic-4.png"},

                  @{@"itemTitle":@"Product 4",
                    @"itemPrice":@"$100.90",
                    @"itemImage":@"PastedGraphic-5.png"},

                  @{@"itemTitle":@"Product 5",
                    @"itemPrice":@"$109.19",
                    @"itemImage":@"PastedGraphic-1.png"},

                  @{@"itemTitle":@"Product 6",
                    @"itemPrice":@"$910.90",
                    @"itemImage":@"PastedGraphic-6.png"},

                  @{@"itemTitle":@"Product 7",
                    @"itemPrice":@"$632.90",
                    @"itemImage":@"PastedGraphic-7.png"},

                  ];

My question is, how I can turn this code into a plist file, so I can get the data of the plist file into the NSCollectionView by using this code:

NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"legue" ofType:@"plist"];
self.contents = [[NSArray alloc] initWithContentsOfFile:plistPath];

Solution

  • NSString *filename = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    // your plist path
    NSString *path = [filename stringByAppendingPathComponent:@"legue.plist"];
    [contents writeToFile:path atomically:YES];
    // test it
    NSString *str = [[NSBundle mainBundle]pathForResource:@"legue.plist" ofType:nil];
    NSLog(@"%@",str); // str = nil; 
    

    So you should create a new plist file,then you can use [NSBundle mainBundle].