NSArray Not Adding To NSMutableArray

Discussion in 'iOS Development' started by Steaps, Jul 6, 2009.

  1. Steaps

    Steaps New Member

    Joined:
    Oct 24, 2007
    Messages:
    5,074
    Likes Received:
    41
    Device:
    iPod touch
    I'm trying to add an NSArray to an NSMutableArray but it just will not add!

    Header File:
    Code:
    NSMutableArray * itemsArray;
    
    Main File:
    Code:
    - (void)loadItemsArray {
    	NSFileManager * fileManager = [NSFileManager defaultManager];
    	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    	NSString *documentsDirectoryPath = [paths objectAtIndex:0];
    	NSString * itemsPath = [documentsDirectoryPath stringByAppendingPathComponent:@"Items.plist"];
    	
    	if ([fileManager fileExistsAtPath:itemsPath]) {
    		NSLog(@"Items.plist exists");
    		itemsArray = [[NSMutableArray alloc] initWithContentsOfFile:itemsPath];
    		NSLog(@"Items Array Count: %d", [itemsArray count]); // Count returns as 2.
    	} else {
    		NSLog(@"File Doesn't Exist");
    		itemsArray = [[NSMutableArray alloc] init];
    	}
    }
    
    - (void)saveItemsArray {
    	NSLog(@"Items Array Count: %d", [itemsArray count]); // Count returns as 0.
    	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    	NSString *documentsDirectoryPath = [paths objectAtIndex:0];
    	NSString * itemsPath = [documentsDirectoryPath stringByAppendingPathComponent:@"Items.plist"];
    	[itemsArray writeToFile:itemsPath atomically:YES];
    }
    
    - (void)addItem:(NSArray *)item {
    	//The array is being sent correctly, have checked with NSLog() statements.
    	NSLog(@"Items Array Count: %d", [itemsArray count]); // Count returns as 0.
    	[itemsArray addObject:item];
    	NSLog(@"Items Array Count: %d", [itemsArray count]); // Count returns as 0.
    	[self saveItemsArray];
    }
    
    Where The Array Is Passed On From:
    Code:
    	NSArray * item = [[NSArray alloc] initWithObjects:[NSString stringWithFormat:@"%@", textField.text], [NSString stringWithFormat:@"%@", textView.text], nil];
    	RootViewController * rootView = [[RootViewController alloc] init];
    	[rootView addItem:item];
    
    Opps, it's because i was creating a new instance of RootViewController, and it hadn't created the itemsArray yet.
  2. jbonedev

    jbonedev New Member

    Joined:
    May 24, 2009
    Messages:
    44
    Likes Received:
    0
    Device:
    iPhone 3G (Black)
    Have you checked that itemsArray is not nil in your addItems method?
    The printf formatting for %d seems to print 0 if you pass nil.
  3. Steaps

    Steaps New Member

    Joined:
    Oct 24, 2007
    Messages:
    5,074
    Likes Received:
    41
    Device:
    iPod touch
    Read the whole post, I fixed the problem, silly mistake.

Share This Page