0

I have an NSMutableArray filled with Task objects. I want to be able to delete those whose completed property are set to YES

    NSMutableArray *allTasks = (NSMutableArray *)[[TaskStore defaultStore] allTasks];

    NSMutableArray *completedTasks;

    for (Task *task in allTasks) {
        if ([task completed]) {
            [completedTasks addObject:task];
        }
    }

    [allTasks removeObjectsInArray:completedTasks];

While debugging I noticed that the completedTasks array is always empty. Why is this?

4 Answers 4

2

You forgot to initialize the completedTasks :

NSMutableArray *completedTasks = [NSMutableArray array];
Sign up to request clarification or add additional context in comments.

Comments

0

You haven't initialized completedTasks. You need to add this:

NSMutableArray *completedTasks = [[NSMutableArray alloc] init];

3 Comments

I have initialized it, just didn't include that part of the code.
Have you verified that the for loop is actually looping through?
Yes, I stepped through it to be sure.
0

You must initialize the array before you can use it, the initializing actually creates your array object -

To do this add This Line to create an autoreleased array (which means you dont have to release it)

NSMutableArray *completedTasks = [NSMutableArray array];

Or

 NSMutableArray *completedTasks = [[NSMutableArray alloc] init];

But then you will have to release it by yourself [completedTasks release] when you are not using it any moere (unless you are using ARC).

This will create your array object.

Shani

1 Comment

it could be both, [NSMutableArray array] is an autorelesed one.
0

from NSMutableArray documentation :

This method assumes that all elements in otherArray respond to hash and isEqual:.

You can try :

 [allTasks filterUsingPredicate:[NSPredicate predicateWithFormat:@"completed = %@", [NSNumber numberWithBool:YES]]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.