Todo Challenge: Why doesn't my solution work?


#1

Hi everybody,

I am having problems doing the Chapter 6 Todo Challenge. When I click the “Add” button, todo items are not added to the list…

Here is my TodoChallenge6AppDelegate.h:

#import <Cocoa/Cocoa.h>

@interface TodoChallenge6AppDelegate : NSObject <NSApplicationDelegate, NSTableViewDataSource, NSTableViewDelegate>

@property (assign) IBOutlet NSWindow *window;
@property (weak) NSMutableArray *items;
@property (weak) IBOutlet NSTextField *inputField;
@property (weak) IBOutlet NSTableView *tableView;

- (IBAction)addTask:(id)sender;
@end

And here is my TodoChallenge6AppDelegate.m:

#import "TodoChallenge6AppDelegate.h"

@implementation TodoChallenge6AppDelegate

@synthesize window = _window;
@synthesize items = _items;
@synthesize inputField = _inputField;
@synthesize tableView = _tableView;

- (id)init
{
    self = [super init];
    if (self) {
        [self setItems:[NSMutableArray array]];
    }
    return self;
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
}

- (IBAction)addTask:(id)sender {
    NSString *task = [[self inputField] stringValue];
    [[self inputField] setStringValue:@""];
    [[self items] addObject:task];
    [[self tableView] reloadData];
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
{
    return (NSInteger)[[self items] count];
}

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
    return [[self items] objectAtIndex];
}
@end

It seems like the items are not added to the NSMutableArray for some reason. Does anyone know what I am doing wrong please?


#2

Ok I figured out the problem: I had to make the NSMutableArray *items strong (not weak). While this fixes the problem, I am not sure why it does…

Can someone explain to me what happened please?


#3

use weak - if you know that there is at least one strong pointer pointing to that object, otherwise you use strong

for IBOutlet, they use weak pointers, because the window view already has strong ptr pointing to it

hope it helps